0

I have to change an attribute of a JSON object. Ex.

allOppList= [[{"A":"2051-11-21","B":"FLOAT"}]]

I have to change the B to "xyz" in the JS file.

I am doing by below code but I am not able to update the B element

let tempAllRecords = Object.assign([], this.allOppList);
        for (let j = 0; j < this.allOppList.length; j++) {
                let tempRec = Object.assign({}, tempAllRecords[j]);
                tempRec.B = event.detail.checked;
                tempAllRecords[j] = tempRec;
        }
        this.allOppList = tempAllRecords;

in this way, "B" of allOppList is not getting updated. Instead, it is getting updated like below

allOppList= [[{"A":"2051-11-21","B":"FLOAT"},"B":"New value"]]
1
  • You have nested arrays, you will need two nested for loops, and you can do this in the inner for loop. – Rahul Gawale Jun 21 at 14:15
1

As a performance matter, do not use for-index loops in LWC within Salesforce, or you'll suffer extreme performance penalties. You do have a nested loop, so the best way to do this is a nested map operation:

let tempAllRecords = this.allOppList.map(
  innerList => innerList.map(
    innerItem => ({ ...innerItem, B: event.detail.checked })
  )
);
3
  • thanks! but getting [e.map is not a function] error – Babu Jun 21 at 15:05
  • @Babu make sure you have an actual list first. You'd get this error if this.allOppList were a String or something else. You may need JSON.parse before you operate on the value if it is an actual JSON string. – sfdcfox Jun 21 at 15:08
  • even after parsing the json I am getting [s.map is not a function] error. let tempData4=JSON.parse(JSON.stringify(this.allOppList[0])); console.log('tempData4>>>>>>>>>>>>'+tempData4); let tempData3 = tempData4.map( innerList => innerList.map( innerItem => ({ ...innerItem, noSeats : chnagedNoSeats }) ) ); – Babu Jun 21 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.