0

I have an array of objects like this:

const arrA = [{a: true}];

And I create a copy of the array like so:

const arrB = Array.from(arrA);

But when I modify the value of the object in arrB, the value in arrA gets modified too.

arrB[0].a = false
// arrB = [{a:false}]
// arrA = [{a:false}] - gets modified also

How do I modify the object values in the cloned array without modifying the original array.

1
  • 1
    The question is then: How do I clone an object? Your array does not care about its contents, cloning an array does not clone the objects in it, it just creates a new array with references to those objects. Maybe try const arrB = Array.from(arrA).map(o => Object.assign({},o)); Commented Dec 12, 2019 at 14:43

2 Answers 2

3

Array.from creates what is called a shallow copy. Shallow copy means you have 2 variables- arrA and arrB pointing at the same array in memory, so you change one it changes the other. With objects inside its even more complicated- cuz even if you manage to create different array in memory- it might still point on the same objects as the previous array, leading to again- one change the changes both.

The opposite is deep copy- creating a new array with new objects that hold the same data values, not references. There are a few methods for that, you can read more here, I recommend on JSON.parse/stringify as the easiest one:

const arrA = [{a: true}];
const arrB = JSON.parse(JSON.stringify(arrA));

This will give you what you want :)

Sign up to request clarification or add additional context in comments.

Comments

1

const arrA = [{a: true}];
const arrB = arrA.map(x => ({...x}))
arrB[0].a = false;
console.log(arrA)
console.log(arrB)

You can use map method to map your older array and create a deep copy of every object using spread operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.