我有许多带有一些键的对象数组:值,其中一个键的值是对象数组。我想将子数组简化为一个新的对象数组。
到目前为止,我还无法找到使用映射的解决方案。
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来做到这一点,但我希望看到一个针对性能进行优化的选项
答案 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);
您还可以使用concat
和map
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);