- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一大堆带有一些键的对象:值,其中一个键的值是一个对象数组。我想将子数组减少为一个新的对象数组。
到目前为止,我无法找到使用映射的解决方案。
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);
您还可以使用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);
关于JavaScript 将原始对象与对象子数组结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56132074/
我正在尝试执行 vagrant up 但一直遇到此错误: ==> default: IOError: [Errno 13] Permission denied: '/usr/local/lib/pyt
我在容器 div 中有一系列动态创建的不同高度的 div。 Varying text... Varying text... Varying text... Varying text.
通过 cygwin 运行 vagrant up 时遇到以下错误。 stderr: /bin/bash: /home/vagrant/.ansible/tmp/ansible-tmp-14872260
今天要向小伙伴们介绍的是一个能够快速地把数据制作成可视化、交互页面的 Python 框架:Streamlit,分分钟让你的数据动起来! 犹记得我在做机器学习和数据分析方面的毕设时,
我是 vagrant 的新手,正在尝试将第二个磁盘添加到我正在用 vagrant 制作的虚拟机中。 我想出了如何在第一次启动虚拟机时连接磁盘,但是当我关闭机器时 然后再次备份(使用 'vagrant
我是一名优秀的程序员,十分优秀!