top of page
  • Twitter
  • LinkedIn
  • YouTube
  • Facebook
  • Instagram

Recent Posts

Salesforce - Adding json key values dynamically in lwc

  • Writer: smartforceit
    smartforceit
  • Feb 21, 2023
  • 1 min read

Lightning Web Component

There are some situations where we need to add field values dynamically. To resolve these type of issue we can add json key and value dynamically in the response received by Apex. See below LWC component for reference


Apex class :

public without sharing class AccHelper {


@AuraEnabled

public static List<Account> getAccList()

{

return [Select Id, Name, AccountNumber,BillingCity,BillingCountry,BillingState, (select Id, Name from contacts) from Account Limit 10];

}

}


accPage.html

<template>

<lightning-button variant="brand" label="show" title="show" onclick={showData}></lightning-button>

<div style="height: 300px;">

<lightning-datatable

key-field="id"

data={data}

columns={columns}

>

</lightning-datatable>

</div>

</template>



accPage.js


import { LightningElement } from 'lwc';

import getAccountList from '@salesforce/apex/AccHelper.getAccList';


const columns = [

{ label: 'PRODUCT NAME', fieldName: 'AccountNumber' },

{ label: 'PRODUCT CODE', fieldName: 'BillingCity' },

{ label: 'PRODUCT FAMILY', fieldName: 'BillingCountry'},

{ label: 'PRODUCT DESCRIPTION', fieldName: 'BillingState'},

{ label: 'KEY CITY', fieldName: 'keyCity'}

];


export default class AccPage extends LightningElement {


data = [];

columns = columns;


connectedCallback()

{

getAccountList().then(response => {

console.log('resp', response);

let updatedResp = [];

for(let i=0; i< response.length; i++)

{

response[i]['keyCity']='X'

}

this.data = response;

}).catch(error => {});

}


showData()

{

getAccountList().then(response => {

console.log('resp', response);

let updatedResp = [];

for(let i=0; i< response.length; i++)

{

var t1 = Object.assign({},response[i]);

t1['keyCity']='x';

updatedResp.push(t1);

}

console.log('resp1', updatedResp);

this.data = updatedResp;

}).catch(error => {});

}

}



for(let i=0; i< response.length; i++)

{

response[i]['keyCity']='X'

}

this.data = response;


Above pseudo code works mostly but there are some cases the response is retrieved in read only mode in that case you need to initialize the object and alter the data. See the below pseudo code

let updatedResp = [];

for(let i=0; i< response.length; i++)

{

var t1 = Object.assign({},response[i]);// object creation

t1['keyCity']='x'; // adding key as ‘keyCity’ and value as ‘x;

updatedResp.push(t1);

}


 
 
 

Comments


logo-sfce.png

AMAZING SERVICES

USEFUL LINKS

CONTACT US

WHO WE ARE

YOUR IT SERVICES COMPANY

Phone no: +91 6301437997
Mail ID :  contact@s4ceit.com

Smartforce IT full-service model is designed to provide our clients with unparalleled domain knowledge and systems expertise across all industries.


All Rights Reserved © 2022 smartforceit.com
 

bottom of page