Home > Back-end >  Why my properties value in my object are duplicated?
Why my properties value in my object are duplicated?

Time:11-06

I created an object "str", which has properties "company","CEO","employees".

As you can see, in properties employees, I created an array containing two objects and both of them have two key/value pairs: "name": "Duke" and "age": 10.

I want to change the propert "name", in the first object has value "Hello" and in the second object is "Hi" but both of two properties have the value "Hi". So why my code does not work ?

// create the values of key "employees"
var employee =[];
var name_age={
"name":"Duke",
"age":10
 };
for(i=0;i<2;i  ){
 employee.push(name_age);
}

 // create object str
 var str = {
"company": "facebook",
"CEO": "Mark Zuckerberg",
"employees":employee
 };
str.employees[0].name="Hello";
str.employees[1].name="Hi";
console.log(str);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Thanks so much

CodePudding user response:

When you are dealing with objects and push them to an array, you are actually pushing their reference. In your code, you are pushing into the array two references but to the same object. Therefore, when you change the property of the reference, it will change for the other one as well. This article can help you: https://javascript.info/object-copy

If you want to create two different objects, you need to use the spread operator. Instead of this line:

employee.push(name_age);

You can use this:

employee.push({...name_age});

CodePudding user response:

I think if you use spread operator you will solve it.

employee.push({...name_age});
  • Related