根据JavaScript中的数组对象列表来操作对象以进行分组
假设我们有一个对象数组,其中包含有关某些汽车的信息,例如:
const arr = [{
"group":[],
"name": "All Makes",
"code": ""
},
{
"group":["Group A"],
"name": "BMW",
"code": "X821"
},
{
"group":["Group B"],
"name": "Audi",
"code": "B216"
},
{
"group":["Group B"],
"name": "Ford",
"code": "P385"
},
{
"group":["Group B", "Group C"],
"name": "Mercedes",
"code": "H801"
},
{
"group":["Group C"],
"name": "Honda",
"code": "C213"
}
];
我们需要编写一个JavaScript函数,该函数接受一个这样的对象数组。该函数应基于每个对象的group属性对该数组的对象进行分组。如果group属性包含多个元素,则该对象应出现在两个组中。
因此。],对于上述数组,输出应类似于-
const output = [{
"group": "Group A",
"cars": [
{
name: "BMW",
code: "X821"
}
]
},
{
"group": "Group B",
"cars": [
{
name: "Audi",
code: "B216"
},
{
name: "Ford",
code: "P385"
},
{
name: "Mercedes",
code: "H801"
}
]
},
{
"group": "Group C",
"cars": [
{
name: "Mercedes",
code: "H801"
},
{
name: "Honda",
code: "C213"
}
]
}
];
示例
为此的代码将是-
const arr = [{
"group":[],
"name": "All Makes",
"code": ""
},
{
"group":["Group A"],
"name": "BMW",
"code": "X821"
},
{
"group":["Group B"],
"name": "Audi",
"code": "B216"
},
{
"group":["Group B"],
"name": "Ford",
"code": "P385"
},
{
"group":["Group B", "Group C"],
"name": "Mercedes",
"code": "H801"
},
{
"group":["Group C"],
"name": "Honda",
"code": "C213"
}
];
const groupTogether = (arr = []) => {
let res = []
res = Object.entries(arr.reduce((acc, { group, ...r }) => {
group.forEach(key => acc[key] = (acc[key] ||
[]).concat({...r}));
return acc;
}, {}))
return res.map(([group, arr]) => ({ group, arr }));
};
console.log(JSON.stringify(groupTogether(arr), undefined, 4));
输出结果
控制台中的输出将是-
[{
"group": "Group A",
"arr": [
{
"name": "BMW",
"code": "X821"
}
]
},
{
"group": "Group B",
"arr": [
{
"name": "Audi",
"code": "B216"
},
{
"name": "Ford",
"code": "P385"
},
{
"name": "Mercedes",
"code": "H801"
}
]
},
{
"group": "Group C",
"arr": [
{
"name": "Mercedes",
"code": "H801"
},
{
"name": "Honda",
"code": "C213"
}
]
}
]
以上是 根据JavaScript中的数组对象列表来操作对象以进行分组 的全部内容, 来源链接: utcz.com/z/321595.html