假设我们有一个像这样的对象-
const obj = { "part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}], "part2":[{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}] };
我们需要编写一个接受一个这样的对象的JavaScript函数。该函数应合并对象的part1和part2以形成对象数组,如下所示:
const output = [ {"id": 1, "a": 50, "b": 40}, {"id": 2, "a": 55}, {"id": 3, "b": 45}, {"id": 4, "a": 100, "b": 110} ];
为此的代码将是-
const obj = { "part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}], "part2":[{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}] }; const mergeObject = (obj = {}) => { let result = []; result = Object.keys(obj).reduce(function (hash) { return function (r, k) { obj[k].forEach(function (o) { if (!hash[o.id]) { hash[o.id] = {}; r.push(hash[o.id]); } Object.keys(o).forEach(function (l) { hash[o.id][l] = o[l]; }); }); return r; }; }(Object.create(null)), []).sort((a, b) => { return a['id'] − b['id']; }); return result; }; console.log(mergeObject(obj));
输出结果
控制台中的输出将是-
[ { id: 1, a: 50, b: 40 }, { id: 2, a: 55 }, { id: 3, b: 45 }, { id: 4, a: 100, b: 110 } ]