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

182
Vistas
JS push object to array by value

How do I push an object to an array by value instead of by reference? Specifically, I want to mutate an object in a for loop and push its value at each iteration. If there is a better way to do this without mutating the object, that works too.

Here is the problem:

> let foo = {"a": 1};
undefined
> let arr = [];
undefined
> for (let i=0;i<10;i++) {
... arr.push(foo);
... foo.a += 1;
... }
11
> arr
[
  { a: 11 }, { a: 11 },
  { a: 11 }, { a: 11 },
  { a: 11 }, { a: 11 },
  { a: 11 }, { a: 11 },
  { a: 11 }, { a: 11 }
]

What I want is arr to have

[
  { a: 1 }, { a: 2 },
  { a: 3 }, { a: 4 },
  { a: 5 }, { a: 6 },
  { a: 7 }, { a: 8 },
  { a: 9 }, { a: 10 }
]

(ignore the off-by-1 error)

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