假设我们有一个像这样的对象数组-
const arr = [{
name : 'Client 1',
total: 900,
value: 12000
}, {
name : 'Client 2',
total: 10,
value: 800
}, {
name : 'Client 3',
total: 5,
value : 0
}];我们需要编写一个JavaScript函数,该函数接受一个这样的数组,并为每个对象属性提取一个单独的数组。
因此,每个对象的name属性使用一个数组,一个用于总计,一个用于值。如果存在更多的属性,我们将分离更多的数组。
为此的代码将是-
const arr = [{
name : 'Client 1',
total: 900,
value: 12000
}, {
name : 'Client 2',
total: 10,
value: 800
}, {
name : 'Client 3',
total: 5,
value : 0
}];
const separateOut = arr => {
if(!arr.length){
return [];
};
const res = {};
const keys = Object.keys(arr[0]);
keys.forEach(key => {
arr.forEach(el => {
if(res.hasOwnProperty(key)){
res[key].push(el[key])
}else{
res[key] = [el[key]];
};
});
});
return res;
};
console.log(separateOut(arr));输出结果
控制台中的输出将是-
{
name: [ 'Client 1', 'Client 2', 'Client 3' ],
total: [ 900, 10, 5 ],
value: [ 12000, 800, 0 ]
}