ภาพรวม
สมมติว่าเรามีอาร์เรย์ของอ็อบเจ็กต์ดังนี้:
const arr = [
{ name: 'Client 1', total: 900, value: 12000 },
{ name: 'Client 2', total: 10, value: 800 },
{ name: 'Client 3', total: 5, value: 0 }
];
เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ดังกล่าวและแยกอาร์เรย์แยกต่างหากสำหรับแต่ละคุณสมบัติของอ็อบเจ็กต์ คือ อาร์เรย์หนึ่งสำหรับ name หนึ่งสำหรับ total และหนึ่งสำหรับ value
ตัวอย่างโค้ด
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 ]
}