0

I want to create a certain number of objects in an array by using new Array().

This works, but as soon as I update one object inside the array, it updates every other object too.

const ar = Array(5).fill({})

console.log(ar)

// will log [{}, {}, {}, {}, {}]

ar[0].hello = 'hi'

console.log(ar)

// will log [{ hello: 'hi' }, { hello: 'hi' }, { hello: 'hi' }, { hello: 'hi' }, { hello: 'hi' }]

The expected result is this:

[{ hello: 'hi' }, {}, {}, {}, {}]

Emre
  • 163
  • 2
  • 10
  • `const ar = Array(5).fill().map(e => ({}));` – ASDFGerte Oct 30 '19 at 14:23
  • This is what's happening: You are creating *one object* **`{}`** and then you put that single object into the array at 5 different spots. Then you change a value of that single object, but no matter which spot you use to update the object, or which spot you use to look at the object, *it is still one object* referenced 5 times. – Peter B Oct 30 '19 at 14:27
  • Thanks for the help, I understand it now what the problem was and it works now the way I want it, thanks a lot. – Emre Oct 30 '19 at 14:40

0 Answers0