【问题标题】:JavaScript combine original object with sub array of objectsJavaScript 将原始对象与子对象数组结合起来
【发布时间】:2019-10-01 13:53:05
【问题描述】:

我有一个带有一些键的大型对象数组:值,其中一个键的值是一个对象数组。我想将子数组缩减为一个新的对象数组。

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

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 做到这一点,但我希望看到一个优化性能的选项

【问题讨论】:

    标签: javascript node.js json object


    【解决方案1】:

    您可以使用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);

    【讨论】:

    猜你喜欢
    • 2010-09-25
    • 2017-10-06
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    相关资源
    最近更新 更多