javascript - 在 JavaScript 中合并两个多维数组的口袋
问题描述
我有两个具有下面给出的结构的数组。
我需要将两个数组的值合二为一,并且顺序应该是按顺序排列的。我也需要保留其他口袋。
标题应该首先是孩子,然后是下一个标题,然后是下一个孩子的口袋。
const header = {
"list": [{
"name": "header-a",
"id": "id-a"
}, {
"name": "header-b",
"id": "id-b"
}]
};
const child = {
"list": [{
"name": "child",
"id": "c1",
'type': "id-a"
},
{
"name": "child 2",
"id": "c2",
'type': "id-a"
},
{
"name": "child 4",
"id": "c4",
'type': "id-b"
},
{
"name": "child-5",
"id": "c5",
'type': "id-b"
}]
};
预期的结果是
const result = {
"list": [{
"name": "header-a",
"header": true,
},
{
"name": "child",
"id": "c1",
'type': "id-a"
},
{
"name": "child 2",
"id": "c2",
'type': "id-a"
},
{
"name": "header-b",
"header": true,
},
{
"name": "child 4",
"id": "c4",
'type': "id-b"
},
{
"name": "child-5",
"id": "c5",
'type': "id-b"
}]
};
解决方案
您遍历标题,对于每个标题,您将类似的项目推入“组合”数组{ name: header.name, header: true }
,然后过滤所有type
等于标题的子项id
并将它们也推入数组:
const header = {
"list": [{
"name": "header-a",
"id": "id-a"
}, {
"name": "header-b",
"id": "id-b"
}]
};
const child = {
"list": [{
"name": "child",
"id": "c1",
'type': "id-a"
},
{
"name": "child 2",
"id": "c2",
'type': "id-a"
},
{
"name": "child 4",
"id": "c4",
'type': "id-b"
},
{
"name": "child-5",
"id": "c5",
'type': "id-b"
}
]
};
const combined = { list: [] };
header.list.forEach(h => {
combined.list.push({ name: h.name, header: true });
child.list.filter(c => c.type === h.id).forEach(c => combined.list.push(c));
});
console.log(combined);
推荐阅读
- javascript - 如何使用javascript设置初始下拉值?
- angular - Angular 2+ 你可以添加/删除基于 html 数据属性的 CSS 类吗?
- php - fread() 和 shell_exec() 返回相同的字符串,但是当我比较它们时,它在我的 PHP 代码中不起作用
- flutter - 超类'Bloc
' 没有零参数构造函数 - java - 不会打开从 eclipse Mac OS 导出的可运行 jar
- css - 样式化 React 组件的一致方法
- javascript - 用多个标签功能替换分割字符串
- reactjs - 空车,firebase-firestore react-hooks
- android - 如何更改华为应用市场中的Provider名称?
- c# - 如何在 C# 中优化 Time-Trigger Azure Function 的性能?