用类似键合并数组中的对象 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' }
]
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP