I just want to push new values to existing object arrays I pull using Apex but when I compile and run what I have below it simply doesn't work. This sounds like a very basic problem but I can't seem to figure it out.
I simply need to pass these new objects/values
isAmount
isPercent
for each of my array list. These new values will be used later on conditional DOM rendering.
Please see a snippet of my code below:
JS
getAccounts({ opptyId : this.recordId})
.then(result => {
this.record = result;
for(let i = 0; i < this.record.length; i++) {
if(this.record[i].DiscountType__c === 'Percent'){
this.record[i].push({isPercent : true, isAmount : false}); // Doesn't work ...
}
if(this.record[i].DiscountType__c === 'Amount'){
this.record[i].push({isAmount : true, isPercent : false}); // Doesn't work ...
}
this.myList = this.record;
this.error = undefined;
})
.catch(error => {
this.error = error;
this.record = undefined;
});
}
I've also tried the following, but to no avail.
this.record.push({isPercent : true, isAmount : false}); // Just creates a new line of array
this.record.push({Id: this.record[i].Id, isPercent : true, isAmount : false}); // Creates a new line of array but with the same Id from an existing one
How do I correctly do this – and is there a better way?
I would appreciate help and suggestions on this. Thanks in advance!
Best Answer
What you're looking for is not push, but map:
This transforms the row by appending two new attributes.
The ... operator copies all the existing properties, while the other two lines add two new calculated properties.