Cho mảng JSON có id trùng lặp:
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 }
];Viết hàm gom nhóm theo id, hợp nhất các key month vào một đối tượng.
Ví dụ
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));Kết quả
Kết quả in ra console:
[
{ 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 }
]