1

I am quite new to Salesforce Apex and dev and there is something I do not get. From what I understood Map are like dictionaries such as { 'Fiat': 'Punto', 'Toyota': 'Aygo }

So I created a map of data in Apex, returned the data and wired my data to my LWC and saved it within a variable let call it param1.

Now I would like to display my data in the LWC. I can do a for each that loop through the data and display the key or the value

but I want to show only 1 piece of data. In python, I could do param1['Fiat'] to get my data value

How can I do it in LWC?

thx you

2 Answers 2

6

If your APEX Controller method returns some Map, for instance Map<String, String> in LWC the returned data structure will be presented as js object, but not as an instance of js Map class. For Instance:

@AuraEnabled(Cacheable=true)
public static Map<String, String> getSomeMap(){
    return new Map<String, String>{ 'Fiat' => 'Punto', 'Toyota' => 'Aygo' };
}
import { LightningElement, wire } from 'lwc';
import getSomeMap from '@salesforce/apex/Test.getSomeMap';

export default class Test extends LightningElement {
    map;

    @wire(getSomeMap)
    wiredContacts({ data }) {
        if (data) {
            this.map = data; // { Fiat: "Punto", Toyota: "Aygo" }
        }
    }
}

To access the object property you can either use

Please note that js is case-sensitive PL.

To display a specific value by key just use getter:

key = 'Fiat';

get value() {
    return this.map?.[this.key];
}

You can use Optional chaining here to prevent TypeError [Cannot read property of undefined]

<template>
    {value}
</template>

Every time when key reactive property changes the value on the markup rerenders.

0
 import { LightningElement, api, track, wire } from 'lwc';
    import { getData} from '@salesforce/apex/classname.getData';
    
    export default class WireFunction extends LightningElement {
        @api recordId;
        @track showData = [];
    
        @wire(getData, { recordId: '$recordId'})
        wiredAccount({ error, data }) {
            if (data) {
           // you can place specific conditions if you need to and then use showData in html 
               this.showData.push(data['Fiat']);
            } 
        }
    
    }

You must log in to answer this question.

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