JavaScript将原始对象与对象的子数组结合在一起

时间:2019-05-14 13:50:29

标签: javascript node.js json object

我有许多带有一些键的对象数组:值,其中一个键的值是对象数组。我想将子数组简化为一个新的对象数组。

到目前为止,我还无法找到使用映射的解决方案。

const warehouse = [
    {
        Server: 'EU',
        Department: 'Paper',
        Suppliers: [
            {
                Name: 'EU Paper',
                Contract: 'Active'
            },
            {
                Name: 'Local Tree',
                Contract: 'Ended'
            }
        ]
    },
    {
        Server: 'US',
        Department: 'Steel',
        Suppliers: [
            {
                Name: 'Steel Research',
                Contract: 'Active'
            },
            {
                Name: 'Heat Vantage',
                Contract: 'Active'
            }
        ]
    }
]

输出应为

const suppliers = [
    {
        Server: 'EU',
        Department: 'Paper',
        Name: 'EU Paper',
        Contract: 'Active'
    },
    {
        Server: 'EU',
        Department: 'Paper',
        Name: 'Local Tree',
        Contract: 'Ended'
    },
    {
        Server: 'US',
        Department: 'Steel',
        Name: 'Steel Research',
        Contract: 'Active'
    },
    {
        Server: 'US',
        Department: 'Steel',
        Name: 'Heat Vantage',
        Contract: 'Active'
    },
]

我可以使用基本的JavaScript来做到这一点,但我希望看到一个针对性能进行优化的选项

1 个答案:

答案 0 :(得分:5)

您可以使用flatMap遍历数组并将结果平坦。使用map遍历Suppliers数组。

const warehouse = [{"Server":"EU","Department":"Paper","Suppliers":[{"Name":"EU Paper","Contract":"Active"},{"Name":"Local Tree","Contract":"Ended"}]},{"Server":"US","Department":"Steel","Suppliers":[{"Name":"Steel Research","Contract":"Active"},{"Name":"Heat Vantage","Contract":"Active"}]}];

let result = warehouse.flatMap(({Suppliers,...r}) => Suppliers.map(o => ({ ...o,...r})));
console.log(result);

您还可以使用concatmap

const warehouse = [{"Server":"EU","Department":"Paper","Suppliers":[{"Name":"EU Paper","Contract":"Active"},{"Name":"Local Tree","Contract":"Ended"}]},{"Server":"US","Department":"Steel","Suppliers":[{"Name":"Steel Research","Contract":"Active"},{"Name":"Heat Vantage","Contract":"Active"}]}];

let result = [].concat(...warehouse.map(({Suppliers,...r}) => Suppliers.map(o => ({ ...o,...r}))));
console.log(result);