我正在尝试克隆数组,重置索引(0,1,3 ......)并将此数组保存在buildingsPayload
变量中:
console.log('1:', this.buildings)
const buildingsPayload = this.buildings.map((building, index) => {
return Object.assign({ index: index }, building)
})
console.log('2:', buildingsPayload)
console.log('1')
中的索引是:
[
{ index: 0 },
{ index: 0 },
{ index: 1 }
]
console.log('2')
中的索引也是:
[
{ index: 0 },
{ index: 0 },
{ index: 1 }
]
如何修改此代码,以便buildingsPayload
最终结果如下:
[
{ index: 0 },
{ index: 1 },
{ index: 2 }
]
答案 0 :(得分:2)
后期对象的键覆盖了Object.assign
中早期对象的键,因此您需要最后指定{ index: index }
:
const buildingsPayload = this.buildings.map((building, index) =>
Object.assign({}, building, { index: index }))