Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter and Assign Object Without Side Effects

Tags:

I currently have the following code:

var myArray = []; var myElement = {   id: 0,   value: 0 }  myElement.id = 0; myElement.value = 1; myArray[0] = myElement;  myElement.id = 2; myElement.value = 3; myArray[1] = myElement; 

The problem is that when I change the value of id and value for my second element, the values also change in the first element. Is there a way that I can keep adding new elements without it changing the value of the previously inserted values in the array?

like image 777
user1219627 Avatar asked Mar 03 '12 05:03

user1219627


People also ask

How do you assign an object in Javascript?

Input : var obj1 = { a: 10 }; var obj2 = { b: 20 }; var obj3 = { c: 30 }; var new_obj = Object. assign(obj1, obj2, obj3); console. log(new_obj); Output : Object { a: 10, b: 20, c: 30 } Explanation: Here in this example the properties of three source objects "obj1, obj2, obj3" are copied to the target object "new_obj".

Why do we use object assign?

assign() This method is used to copy one or more source objects to a target object. It invokes getters and setters since it uses both 'get' on the source and 'Set' on the target.

What does ES6 object assign do?

assign() method in ES6. The Object. assign() copies all enumerable and own properties from the source objects to the target object. It returns the target object.


1 Answers

Try this instead:

var myArray = [];  myArray.push({ id: 0, value: 1 }); myArray.push({ id: 2, value: 3 }); 

or will this not work for your situation?

like image 200
kendaleiv Avatar answered Nov 22 '22 23:11

kendaleiv