在 JavaScript 中重组 JSON 数组
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的 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 }
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

