为什么没有为跟随克隆数组正确设置索引?

时间:2017-06-30 04:01:23

标签: javascript

我正在尝试克隆数组,重置索引(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 }
]

1 个答案:

答案 0 :(得分:2)

后期对象的键覆盖了Object.assign中早期对象的键,因此您需要最后指定{ index: index }

const buildingsPayload = this.buildings.map((building, index) =>
  Object.assign({}, building, { index: index }))