0

JSON object:

{
    "Number__c": "65-412",
    "Label__c": null,
    "parent__c": "",
    "Packages__c": 2,
    "Name": "343"
}

I can see the value of parent__c when I log to the console like:

dataTable.forEach(function(li) {
    console.log('li.parent__c----++++++++++---'+ li.parent__c);
    li.parent__c = this.otherParentId;
});

when I try and set it to another value (in the second line of the loop) it silently fails. What is the technique to accomplish this?

0
1

In JavaScript, this is a fickle thing. Notably, using this inside a proper function() may access that function's property, and not the one you expected. The main resolution to this is to use an arrow function:

dataTable.forEach((li) => {
    console.log('li.parent__c----++++++++++---'+ li.parent__c);
    li.parent__c = this.otherParentId;
});

This simple modification makes it so that this is whatever was in scope when the function was defined, which is usually what you wanted anyways (and one of the primary motivations for this function to have been implemented).

Alternatively, when you're modifying data, it's usually better to map the data instead:

dataTable = dataTable.map(row => ({...row, parent__c: this.otherParentId }));
0
    let revisedDataTable = dataTable.draftValues;
    
    for (var i=0; i<revisedDataTable.length; i++) {
        revisedDataTable[i]["parent__c"] = this.otherParentId;
        if (revisedDataTable[i].Id.includes("row-")) {
            revisedDataTable[i].Id = "";
        }
    }

I was able to make it work with this. revisedDataTable is in an array instead of just JSON like above:

[{
    "Id": "12345"
    "Number__c": "65-412",
    "Label__c": null,
    "parent__c": "",
    "Packages__c": 2,
    "Name": "343"
}]

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.