重新组合JavaScript中的JSON数组
假设我们有一个这样的对象的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 }
]