Copying objects from objects

Copying objects from objects
0

#1

I know how to copy an object itself but here is my question:
Here it is an object:

let obj = [
    {val: [2], something: 9}
];

As you can see val: has an array as a value.

Now I want to copy that array and manipulate it

let change = [];
change =  obj[0].val;

change.push(8);

And now I have changed -->“change” and val together

 console.log(change);
console.log(obj[0].val);
console.log(obj);

So My question is how to change only the “change” without changing array in object “obj” ?
In other words how to copy an object from an object ?

Regards


#2

Instead of this, you can use this:

 change.push(...(obj[0].val))

The three dots in above code are spread operator.
Does that help?


#3

Hi,
Here is an interesting post on the topic : https://scotch.io/bar-talk/copying-objects-in-javascript
using (=) will not copy the object, it will only create a different reference to the same object.


#4

Yes thanks, it solve a problem , but frankly I was wondering if I can do this in this way change = and here some code to write :wink:


#5

Thanks I will review it , copying objects is not so obvious if there are more nested objects :wink:


#6

Ok wrote it in this way :wink:

change = […(obj[0].val)];