0

I initialized array with default object and I want to update property in one element. Unfortunately there are updated all elements of list. My code is following:

let object = {person: {
  name: '',
  age: 0
}};

let list = [...Array(2)].map(x => ({...object}));

list[0].person.name = 'John';

var myJSON = JSON.stringify(list);
document.getElementById("demo").innerHTML = myJSON;
<p id="demo"></p>

What is problem with this?

2 Answers 2

1

Of course

let object = {person: {
  name: '',
  age: 0
}};

let list = [...Array(2)].map(x => ({...object}));
console.log( 'object are differents', list[0] !== list[1] );
console.log( 'person are differents', list[0].person !== list[1].person );

Just change with

let object = {person: {
  name: '',
  age: 0
}};

let list = [...Array(2)].map(x => ({ person: {name:'', age:0}}) );
console.log( 'object are differents', list[0] !== list[1] );
console.log( 'person are differents', list[0].person !== list[1].person );

Your error is that destructuring is not a deep copy. So you use always the same person object.

{...object}
is same as
{ person: object.person }

Edition

As you want a deep copy of object, this is how you can do it very simply:

let object = {person: {
  name: '',
  age: 0
}};

let list = [...Array(2)].map(x => {
   return JSON.parse(JSON.stringify(object));
});

console.log( 'object are differents', list[0] !== list[1] );
console.log( 'person are differents', list[0].person !== list[1].person );

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

3 Comments

Is method to create new object depend on created object? It is only sample, but I have really complex object with initialization in many places with inheriting. I thought using {...object} instead of object will create for me new object.
So create it with const new = JSON.parse(JSON.stringify(object));to have a deep copy, I will edit the answer
Now whatever your object is, you will have a totally deep copy of it
0

Your problem is that your creating a copy of your object twice .map(x => ({...object})) but inside your object you have another object, that one is not copied. so the copy has a property "person" that is pointing to the same place in memory, you need to either do a deep copy or just add new empty objects.

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.