Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

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

employee.push({...name_age});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda