Skip to content Skip to sidebar Skip to footer

How To Update One Javascript Object Array Without Updating The Other

I created an object array with some values. Then I created another object array and initialized it with the first one. Then I pushed a value in 2nd array, and console logged both a

Solution 1:

Assignment such as var b = a for a object creates an object 'b' which references(just like pointer) the same location pointed by 'a', in general. You may find this link helpful.

However you can create/clone a new array with slice method. var b = a.slice()

Solution 2:

You can use

var b = JSON.parse(JSON.stringify(a));

https://stackoverflow.com/a/4591639/1623259

Solution 3:

Both are pointing to the same values in the memory when you say:

var b = a;

So if you change a, b will be affected and vice versa, you need to copy using a loop.

EDIT

use this line of code which I get from this post

var b= a.slice(0); 

Post a Comment for "How To Update One Javascript Object Array Without Updating The Other"