3

JS Map Value

@track currentSelectedProduct = '{"01t1s000000j70VAAQ":{"Id":"01t1s000000j70VAAQ","Name":"test","ProductCode":"200299060003","Number__c":"CRM-000001","MOQ__c":10,"StandardCost__c":10,"Description":"Test"}}'

HTML Code

<template>
        <div class="slds-box" if:true={showSelectedRecord}>
            <table class="slds-table">
                <tbody for:each={currentSelectedProduct} for:item="pro" key={pro.id}>
                    <tr class="slds-hint-parent">
                        <td>
                            <div class="slds-truncate" >{pro.Name}</div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
</template>

I know that if "currentSelectedProduct" is a List, there will be no problem with this. But "currentSelectedProduct" is a Map, what do I need to do?

2 Answers 2

5

You are likely need to make the object iterable to use it in for:each statement. To do that you can create a getter inside your class. Since the component will rerender each time the data is updated, the getter result will be updated as well. The easiest option would be to use Object.entries and then transform array [key, value] to object {key: key, value: value}. Please see the full code below.

export default class extends LightningElement {
    @track currentSelectedProduct = '{"01t1s000000j70VAAQ":{"Id":"01t1s000000j70VAAQ","Name":"test","ProductCode":"200299060003","Number__c":"CRM-000001","MOQ__c":10,"StandardCost__c":10,"Description":"Test"}}'
    get currentSelectedProductList() {
        return Object.entries(this.currentSelectedProduct).map([key, value] => {key, value});
    }
}
<template>
        <div class="slds-box" if:true={showSelectedRecord}>
            <table class="slds-table">
                <tbody for:each={currentSelectedProductList} for:item="pro" key={pro.key}>
                    <tr class="slds-hint-parent">
                        <td>
                            <div class="slds-truncate" >{pro.value.Name}</div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
</template>
1

You need to extract the detail you want to present into a (tracked) array instead of a map. LWC template handling is quite unsophisticated and only provides array iteration with template for:each.

1
  • 1
    How would you do it ?
    – Ben2pop
    Jun 10, 2021 at 8:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .