gpt4 book ai didi

JavaScript 将原始对象与对象子数组结合起来

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:44 25 4
gpt4 key购买 nike

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

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

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 来完成此操作,但我希望看到一个优化性能的选项

最佳答案

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

关于JavaScript 将原始对象与对象子数组结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56132074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com