In this post, we will look at how to create an object dynamically in LWC and pass it as a Map from LWC to apex class.

In this example, we are using a string whose value is of format ‘text=test,input=abc’. This value can also be passed as a @api property to LWC.

We will first split the string using split() and will create an object from it dynamically. We will then pass the newly created object to the Apex class. Object from LWC is received as a Map in Apex.

LWC -
import { LightningElement, api } from 'lwc';
import demoMethod from '@salesforce/apex/DemoClass.demoMethod';

export default class PassMapFromLwcToApexDemo extends LightningElement {

    @api input;

    connectedCallback()
    {
        let mapParameters = {};
        const myArray = this.input.split(",");
        myArray.forEach(element => {
            let keyValue = element.split("=");
            mapParameters[keyValue[0]] = keyValue[1]; //Dynamically setting the property and values of the object
        });

        demoMethod({mapParameters : mapParameters});
    }

}

Apex Class -
public with sharing class DemoClass {
    
    @AuraEnabled
    public static void demoMethod(Map<String, Object> mapParameters) 
    {
        System.debug('Parameters '+ mapParameters);
    	System.debug('Text '+ mapParameters.get('text'));
    }
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *