Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
Why my properties value in my object are duplicated?

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);

Thanks so much

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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});
about 4 years ago · Juan Pablo Isaza Report

0

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

employee.push({...name_age});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!