[英]How to Merge array of objects list into single array
I have a list of array of Objects.我有一个对象数组列表。 I need to concat the all the
options
items into one array.我需要将所有
options
项目连接到一个数组中。 Here is the sample array of objects.这是对象的示例数组。
let data = [
{
name: "group1",
options: [
{
item: "item1",
price: 100
},
{
item: "item2",
price: 200
},
{
item: "item3",
price: 300
}
]
},
{
name: "group2",
options: [
{
item: "item4",
price: 101
},
{
item: "item5",
price: 201
}
]
},
{
name: "group3",
options: [
{
item: "item6",
price: 254
},
{
item: "item7",
price: 358
}
]
}
]
output like:输出如:
let options = [
{
item: "item1",
price: 100
},
{
item: "item2",
price: 200
},
{
item: "item3",
price: 300
},
{
item: "item4",
price: 101
},
{
item: "item5",
price: 201
},
{
item: "item6",
price: 254
},
{
item: "item7",
price: 358
}
]
你可以用reduce
做到这一点:
const options = data.reduce((acc, item) => acc.concat(item.options), [])
You can try with Array.prototype.flatMap()
您可以尝试使用
Array.prototype.flatMap()
The
flatMap()
method first maps each element using a mapping function, then flattens the result into a new array.flatMap()
方法首先使用映射函数映射每个元素,然后将结果展平到一个新数组中。 It is identical to amap()
followed by aflat()
of depth 1, butflatMap()
is often quite useful, as merging both into one method is slightly more efficient.它与
map()
后跟一个深度为1 的flat()
相同,但flatMap()
通常非常有用,因为将两者合并为一种方法效率更高。
let options = data.flatMap(d => d.options);
let data = [ { name: "group1", options: [ { item: "item1", price: 100 }, { item: "item2", price: 200 }, { item: "item3", price: 300 } ] }, { name: "group2", options: [ { item: "item4", price: 101 }, { item: "item5", price: 201 } ] }, { name: "group3", options: [ { item: "item6", price: 254 }, { item: "item7", price: 358 } ] } ]; let options = data.flatMap(d => d.options); console.log(options);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.