假设我们有两个对象的子级和父级JSON数组,如下所示:
const child = [{ id: 1, name: 'somename', parent: { id: 2 }, }, { id: 2, name: 'some child name', parent: { id: 4 } }]; const parent = [{ id: 1, parentName: 'The first', child: {} }, { id: 2, parentName: 'The second', child: {} }, { id: 3, parentName: 'The third', child: {} }, { id: 4, parentName: 'The fourth', child: {} }];
我们需要编写一个接受这两个数组的JavaScript函数。
并且我们的函数应该将子数组对象合并到相应的父对象中。
因此,最终输出应如下所示:
const output = [ { id: 1, parentName: The first, child: {} }, { id: 2, parentName: The second, child: { id: 1, name: somename, } }, { id: 3, parentName: The third, child: {} }, { id: 4, parentName: The fourth, child: { id: 2 name: some child name, } }, ];
为此的代码将是-
const child = [{ id: 1, name: 'somename', parent: { id: 2 }, }, { id: 2, name: 'some child name', parent: { id: 4 } }]; const parent = [{ id: 1, parentName: 'The first', child: {} }, { id: 2, parentName: 'The second', child: {} }, { id: 3, parentName: 'The third', child: {} }, { id: 4, parentName: 'The fourth', child: {} }]; const combineParentChild = (parent, child) => { const combined = []; for (let i = 0; i < parent.length; i++) { for (let j = 0; j < child.length; j++) { if (child[j].parent.id === parent[i].id) { parent[i].child.id = child[j].id; parent[i].child.name = child[j].name; break; }; }; combined.push(parent[i]) }; return combined; }; console.log(combineParentChild(parent, child));
输出结果
控制台中的输出将是-
[ { id: 1, parentName: 'The first', child: {} }, { id: 2, parentName: 'The second', child: { id: 1, name: 'somename' } }, { id: 3, parentName: 'The third', child: {} }, { id: 4, parentName: 'The fourth', child: { id: 2, name: 'some child name' } } ]