0

I've looked around a good amount on stackoverflow and haven't found this question yet. I feel like I'm missing something obvious so it's possible the question exists and I couldn't find it. My issue is that I'm trying to create an array of objects with different id's. When I run the for loop and update the id's based on the value of i, the resulting array has id's that are all the same.

Here's a sample snippet -

const baseObj = {
    nestedId: {
      id: 1,
  }
}

const objArr = [];
for(let i=0; i<3; i++) {
    const newObj = {...baseObj}
    newObj.nestedId.id = i + 1;
    objArr.push(newObj)
}

The resulting array is full of objects with the same id

{
  id: 3
}

I'm unsure what to do so I can make each id be different. Any help greatly appreciated.

  • `{...baseObj}` only creates a shallow copy, you need a deep copy – CertainPerformance Jul 15 '22 at 19:02
  • thanks @CertainPerformance. Changing the copy to use JSON.parse(JSON.stringify(baseObj)) fixes the problem. If you don't mind, can you clarify what's happening under the hood and why that fixes it? I'm not understanding why they all got the value 3, even if it is a shallow copy. – cuomo24 Jul 15 '22 at 19:10

0 Answers0