สมมติว่าเรามีอาร์เรย์ JSON ของวัตถุเช่นนี้ -
const arr = [
{
"id": "03868185",
"month_10": 6,
},
{
"id": "03870584",
"month_6": 2,
},
{
"id": "03870584",
"month_7": 5,
},
{
"id": "51295",
"month_1": 1,
},
{
"id": "51295",
"month_10": 1,
},
{
"id": "55468",
"month_11": 1,
}
]; ในที่นี้ เราจะเห็นได้ว่าคุณสมบัติ "id" เดียวกันกำลังถูกทำซ้ำในบางออบเจกต์ เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าวที่มีคู่คีย์/ค่าทั้งหมดสำหรับคุณสมบัติ "id" เฉพาะที่จัดกลุ่มไว้ในวัตถุเดียว
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const arr = [
{
"id": "03868185",
"month_10": 6,
},
{
"id": "03870584",
"month_6": 2,
},
{
"id": "03870584",
"month_7": 5,
},
{
"id": "51295",
"month_1": 1,
},
{
"id": "51295",
"month_10": 1,
},
{
"id": "55468",
"month_11": 1,
}
];
const groupById = (arr = []) => {
const map = {};
const res = [];
arr.forEach(el => {
if(map.hasOwnProperty(el['id'])){
const index = map[el['id']] - 1;
const key = Object.keys(el)[1];
res[index][key] = el[key];
}
else{
map[el['id']] = res.push(el);
}
})
return res;
};
console.log(groupById(arr)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[
{ id: '03868185', month_10: 6 },
{ id: '03870584', month_6: 2, month_7: 5 },
{ id: '51295', month_1: 1, month_10: 1 },
{ id: '55468', month_11: 1 }
]