使用相似的关键JavaScript合并数组中的对象
假设我们有以下对象数组-
const arr = [ {id: 1, h1: 'Daily tests'}, {id: 2, h1: 'Details'}, {id: 1, h2: 'Daily classes'}, {id: 3, h2: 'Results'}, {id: 2, h3: 'Admissions'}, {id: 1, h4: 'Students'}, {id: 2, h5: 'Alumni'}, {id: 3, h3: 'Appreciations'}, {id: 1, h5: 'Tiny Tots'}, {id: 1, h6: 'Extras'}, ];
我们必须编写一个函数,将该数组转换为一个数组,在该数组中,具有相同id的所有标题(h1,h2,h3…)都合并在同一对象内。因此,让我们为该函数编写代码-
示例
const arr = [ {id: 1, h1: 'Daily tests'}, {id: 2, h1: 'Details'}, {id: 1, h2: 'Daily classes'}, {id: 3, h2: 'Results'}, {id: 2, h3: 'Admissions'}, {id: 1, h4: 'Students'}, {id: 2, h5: 'Alumni'}, {id: 3, h3: 'Appreciations'}, {id: 1, h5: 'Tiny Tots'}, {id: 1, h6: 'Extras'}, ]; const clubArray = (arr) => { return arr.reduce((acc, val, ind) => { const index = acc.findIndex(el => el.id === val.id); if(index !== -1){ const key = Object.keys(val)[1]; acc[index][key] = val[key]; } else { acc.push(val); }; return acc; }, []); }; console.log(clubArray(arr));
输出结果
控制台中的输出将为-
[ { id: 1, h1: 'Daily tests', h2: 'Daily classes', h4: 'Students', h5: 'Tiny Tots', h6: 'Extras' }, { id: 2, h1: 'Details', h3: 'Admissions', h5: 'Alumni' }, { id: 3, h2: 'Results', h3: 'Appreciations' } ]