Reputation: 7601
I'm trying to clone an array, reset the index (0, 1, 3 ...) and save this array in a buildingsPayload
variable:
console.log('1:', this.buildings)
const buildingsPayload = this.buildings.map((building, index) => {
return Object.assign({ index: index }, building)
})
console.log('2:', buildingsPayload)
The index in console.log('1')
is:
[
{ index: 0 },
{ index: 0 },
{ index: 1 }
]
And the index in console.log('2')
is also:
[
{ index: 0 },
{ index: 0 },
{ index: 1 }
]
How to modify this code so buildingsPayload
ends up like:
[
{ index: 0 },
{ index: 1 },
{ index: 2 }
]
Upvotes: 0
Views: 24
Reputation: 225044
Later objects’ keys override those of earlier objects in Object.assign
, so you need to specify { index: index }
last:
const buildingsPayload = this.buildings.map((building, index) =>
Object.assign({}, building, { index: index }))
Upvotes: 2