다음과 같은 객체의 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" 속성이 반복되는 것을 볼 수 있습니다. 우리는 하나의 단일 객체로 그룹화된 특정 "id" 속성에 대한 모든 키/값 쌍을 포함하는 하나의 배열을 취하는 JavaScript 함수를 작성해야 합니다.
예시
이에 대한 코드는 -
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 }
]