将同一对象数组中的多个数组组合在一起

时间:2019-03-21 19:52:18

标签: javascript arrays

我有这个对象数组

const line_items = [
    {
        id: 1,
        components: [
            { name: "nadia" },
            { name: "tim" },
            { name: "mark" },
            { name: "alex" }
        ]
    }, {
        id: 1,
        components: [ 
            { name: "ramsey" } 
        ]
    }
];

我想将所有组件组合成一个数组。结果将是

[
    { name: "nadia" },
    { name: "tim" },
    { name: "mark" },
    { name: "alex" },
    { name: "ramsey" }
]

我的尝试

function pretty(obj) { return JSON.stringify(obj, null, 2) }

const line_items = [
    {
        id: 1,
        components: [
            { name: "nadia" },
            { name: "tim" },
            { name: "mark" },
            { name: "alex" }
        ]
    }, {
        id: 1,
        components: [ 
            { name: "ramsey" } 
        ]
    }
];

const all_components = line_items;

console.log(pretty(all_components));

4 个答案:

答案 0 :(得分:4)

您可以使用Array.flatMap()(IE / Edge不支持):

const line_items = [{"id":1,"components":[{"name":"nadia"},{"name":"tim"},{"name":"mark"},{"name":"alex"}]},{"id":1,"components":[{"name":"ramsey"}]}];

const all_components = line_items.flatMap(o => o.components);

console.log(pretty(all_components));

function pretty(obj) { return JSON.stringify(obj, null, 2) }

如果不支持flatMap,则可以将Array.map()与spread和Array.concat()结合使用:

const line_items = [{"id":1,"components":[{"name":"nadia"},{"name":"tim"},{"name":"mark"},{"name":"alex"}]},{"id":1,"components":[{"name":"ramsey"}]}];

const all_components = [].concat(...line_items.map(o => o.components));

console.log(pretty(all_components));

function pretty(obj) { return JSON.stringify(obj, null, 2) }

答案 1 :(得分:1)

您可以使用reduce(),并使用Rest参数将组件传递到concat()

const line_items = [
    {
        id: 1,
        components: [
            { name: "nadia" },
            { name: "tim" },
            { name: "mark" },
            { name: "alex" }
        ]
    }, {
        id: 1,
        components: [ 
            { name: "ramsey" } 
        ]
    }
];

let allcomps = line_items.reduce((ac,a) => ac.concat(...a.components),[])
console.log(allcomps)

答案 2 :(得分:1)

您可以使用减少项目。

const
    line_items = [{ id: 1, components: [{ name: "nadia" }, { name: "tim" }, { name: "mark" }, { name: "alex" }] }, { id: 1, components: [{ name: "ramsey" }] }],
    result = line_items.reduce((r, { components }) => [...r, ...components], []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

您可以为此使用flatMap

const line_items = [
    {
        id: 1,
        components: [
            { name: "nadia" },
            { name: "tim" },
            { name: "mark" },
            { name: "alex" }
        ]
    }, {
        id: 1,
        components: [ 
            { name: "ramsey" } 
        ]
    }
];

var result = line_items.flatMap((i)=>{ return i['components'];});

console.log(result);