0

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)

The Bic Pen
  • 773
  • 6
  • 21
  • Very closely related to [Modifying a copy of a JavaScript object is causing the original object to change](https://stackoverflow.com/questions/29050004/modifying-a-copy-of-a-javascript-object-is-causing-the-original-object-to-change) – Ivar Dec 05 '21 at 20:40
  • Move `let foo = { "a": 1 };` inside the loop. This way more than one object gets created. – Sebastian Simon Dec 05 '21 at 20:47

0 Answers0