1

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!

2
  • The <lightning-data-table> and the <lightning-tree-grid> are both suffering from this issue when pushing a new item in the doesn't re-render the component. Are you using the myList property with one of those components or with a different component?
    – pmdartus
    Commented May 27, 2020 at 14:51
  • I'm actually using a Custom Data Table to which, when given the right attributes, myList successfully re-renders. @pmdartus Commented May 27, 2020 at 15:19

1 Answer 1

5

What you're looking for is not push, but map:

this.record = result;
this.myList = this.record.map(row => ({
  ...row,
  isPercent: row.DiscountType__c==='Percent',
  isAmount: row.DiscountType__c==='Amount'
}));

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.

1
  • Excellent, I just tried it and it works! With fewer lines of code as well. Thanks, @sfdcfox. Commented May 26, 2020 at 12:32

You must log in to answer this question.

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