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)