将值添加到映射数组
我有一个array这样的价值观:
0:
code: "fb"
description: "Not relevant text."
did: 1
name: "Some random name"
sortOrder: 1
1:
code: "fr"
description: "Not relevant text."
did: 2
name: "Some random name"
sortOrder: 2
当我像这样映射数组时:
values: this.stackOverflowExample.map(v => v.code).push(null)
和push一个null 代码集,它将所有值设置为null
我想要的输出:
values: [
0: 'fb'
1: 'fr'
2: null ]
我得到的输出:
values: 3
如何添加值的数组this.stackOverflowExample
是由映射code,而不影响其他值?
回答
该push方法返回数组的新长度而不是变异的数组,请参阅文档。
如果您只想附加null到映射的数组,您可以:
连接你的映射数组[null]
values: anArray.map(mapFn).concat([null])
将您的映射数组散布在一个数组中,最后一项是null
values: [...anArray.map(mapFn), null]
- You may have forgotten to [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) your mapped array. `.concat([null])` works too. I will update my answer to clarify this and add the other option.