สมมติว่าเรามีอาร์เรย์ของวัตถุเช่นนี้ -
const arr = [
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
] เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าวหนึ่งอาร์เรย์ และให้ผลตอบแทน (ส่งคืน) อาร์เรย์ใหม่
ในอาร์เรย์ใหม่ คีย์ลูกค้าทั้งหมดที่มีค่าเดียวกันควรถูกรวมเข้าด้วยกัน และผลลัพธ์ควรมีลักษณะดังนี้ -
const output = [
{
"Customer 1": {
"projects": "1"
}
},
{
"Customer 2": {
"projects": [
"2",
"3"
]
}
}
] ตัวอย่าง
ให้เราเขียนโค้ด -
const arr = [
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
]
const groupCustomer = data => {
const res = [];
data.forEach(el => {
let customer = res.filter(custom => {
return el.customer === custom.customer;
})[0];
if(customer){
customer.projects.push(el.project);
}else{
res.push({ customer: el.customer, projects: [el.project] });
};
});
return res;
};
console.log(groupCustomer(arr)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[
{ customer: 'Customer 1', projects: [ '1' ] },
{ customer: 'Customer 2', projects: [ '2', '3' ] }
]