将值添加到映射数组

我有一个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.

以上是将值添加到映射数组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>