JavaScript中的合并和分组对象属性
假设我们有一个像这样的对象数组-
const arr = [ {name: 'lorem', age: 20, color:'red'}, {name: 'lorem', weight: 1, height:5} , {name: 'hello', ipsum : 'dolor'} ];
我们需要编写一个JavaScript函数,该函数接受一个这样的对象数组。该函数应将具有“name”属性值的那些对象的所有属性分组。
例如-
对于上面的数组,输出应类似于-
const output = [ {name: 'lorem', age : 20, color: 'red', weight : 1, height : 5}, {name: 'hello', ipsum : 'dolor'} ];
示例
为此的代码将是-
const arr = [ {name: 'lorem', age: 20, color:'red'}, {name: 'lorem', weight: 1, height:5} , {name: 'hello', ipsum : 'dolor'} ]; const mergeList = (arr = []) => { const temp = {}; arr.forEach(elem => { let name = elem.name; delete elem.name; temp[name] = { ...temp[name], ...elem }; }); const res = []; Object.keys(temp).forEach(key => { let object = temp[key]; object.name = key; res.push(object); }); return res; }; console.log(mergeList(arr));
输出结果
控制台中的输出将是-
[ { age: 20, color: 'red', weight: 1, height: 5, name: 'lorem' }, { ipsum: 'dolor', name: 'hello' } ]