LWC HTML – How to Refer to the MAP Value in JavaScript

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?

Best Answer

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>
Related Topic