组合数组对象以在 JavaScript 中创建新的数组对象



如何通过在数组中组合数组对象来创建新的数组对象。 我有obj,在每个对象中组合items数组,并在javascript中形成新的数组对象。


function newarray(obj){
return obj.map(e=>e.items);
}
var obj =[
{
"id": 1,
"store": "10",
"items": [
{
"name": "sample1",
"total": 20,
"store": "10"
},
{
"name": "sample2",
"total": 10,
"store": "10"
}
]
},
{
"id": 1,
"store": "11",
"items": [
{
"name": "sample3",
"total": 10,
"store": "11"
},
{
"name": "sample4",
"total": 10,
"store": "11"
}
]
}
]

预期输出:

[
{
"name": "sample1",
"total": 20,
"store": "10"
},
{
"name": "sample2",
"total": 10,
"store": "10"
},
{
"name": "sample3",
"total": 10,
"store": "11"
},
{
"name": "sample4",
"total": 10,
"store": "11"
}
]

您可以使用地图+平面

const obj = [
{
id: 1,
store: '10',
items: [
{
name: 'sample1',
total: 20,
store: '10',
},
{
name: 'sample2',
total: 10,
store: '10',
},
],
},
{
id: 1,
store: '11',
items: [
{
name: 'sample3',
total: 10,
store: '11',
},
{
name: 'sample4',
total: 10,
store: '11',
},
],
},
];
const result = obj.map(o => o.items).flat();
console.log(result);

你可以用Array#flatMap进行单循环。

const
flat = array => array.flatMap(({ items }) => items),
array = [{ id: 1, store: "10", items: [{ name: "sample1", total: 20, store: "10" }, { name: "sample2", total: 10, store: "10" }] }, { id: 1, store: "11", items: [{ name: "sample3", total: 10, store: "11" }, { name: "sample4", total: 10, store: "11" }] }],
result = flat(array);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

只有reduce也可以工作:

const combined = obj.reduce((acc, item) => {
return [ ...acc, ...item.items ];
}, []);
console.log(combined)

最新更新