0

I am trying to save a new values into an Object from a modal, but not pushing it yet to the database. I successfully pushed the new values to the Object, but once I wanted to push another value into the Object, the previous inserted value was changed as well.

Upon creating the 1st value enter image description here

When I add another one or the 2nd value enter image description here

Notice that the Test 1 values was changed to the values of the recently added ones

Here's what I have so far:

saveModal : function(component, event, helper){
    var newAccountForm = component.get("v.accountForm");
    var accountList = component.get("v.accountList");
    var newAccList = [...accountList,newAccountForm];
    component.set("v.accountList",newAccList);
    helper.closeModal(component,event,helper);
},

I tried to do this accountList.push(newAccountForm) but I get the same results, the previous inserted value was changed as well, it mirrors the latest value added.

On my 2nd creation/save, the new inserted accountList value was change prior to setting its new value.

1 Answer 1

1

In Object-Oriented Programming, we have the concept of "references." Multiple variables can refer to the same physical object in memory.

For example, observe the following:

let x = { value: 10 }
let y = x;
y.value = 20;
console.log(x.value); // 20

Because both variables point to the same object, you only have one object, so a change in one variable will appear to change the other as well.

To fix this, copy the object:

var newAccList = [...accountList,{...newAccountForm}];

Where {...someObject} will make a new object with a copy of the top-level elements (it is a "shallow" copy).

To illustrate with our example, above:

let x = { value: 10 }
let y = {...x};
y.value = 20;
console.log(x.value); // 10
console.log(y.value); // 20

If you happen to need a recursive, or "deep", copy, you'll want to do some research on such as method. In many cases, it can be written as:

var newAccList = [...accountList,JSON.parse(JSON.stringify(newAccountForm))];

Where we make a round-trip through a JSON string. This won't work for self-referential structures, though:

var value = { word: 'bird' }
value.otherWord = value;

See more information in this answer on Stack Overflow.

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.