我有一个名为rate的对象数组。在每个rate对象中都有一个tags属性。我想将所有对象的标签组合到新的数组中,这样期望的输出是:
["TAG_1_2_3_4", "TAG_7_8_9_0", "TAG_4_5_6"]有没有比使用forEach遍历然后推送到数组更简单/干净的方法?
示例:
[
{
"price": "123",
"tags": [
"TAG_1_2_3_4",
"TAG_7_8_9_0"
]
},
{
"price":"456",
"tags":[
"TAG_4_5_6"
]
}
]发布于 2020-12-01 04:05:56
使用Array.flatMap()获取tags并将其展平为单个数组:
const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]
const result = arr.flatMap(o => o.tags)
console.log(result)
如果不支持Array.flatMap(),则可以将Array.reduce()与Array.concat()一起使用
const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]
const result = arr.reduce((acc, o) => acc.concat(o.tags), [])
console.log(result)
或者使用Array.map()获取所有tags,并通过扩展到Array.concat()来实现扁平化
const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]
const result = [].concat(...arr.map(o => o.tags))
console.log(result)
https://stackoverflow.com/questions/65080379
复制相似问题