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?
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".
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With