使用 JavaScript 按键连接两个对象
假设我们有两个类似于以下示例中的子和父 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' } } ]
广告