使用相似的关键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' }
]热门推荐
5 短祝福语简短暖心
10 结婚祝福语粤语大全简短
11 晚上祝福语女生文案简短
12 法语妈妈生日祝福语简短
13 药厂开工祝福语大全简短
14 蛋糕节日祝福语简短英文
15 跨年的生日祝福语简短
16 文案祝福语英文短句简短
17 在家聚餐婚礼祝福语简短
18 学生节祝福语大全简短