问题描述
var arraJson = [
{
"name" : "a","department: "a"
},{
"name" : "b",{
"name" : "c","department: "b"
}]
预期输出
output = [
{
"department" : "a","employee" ["a","b"]
},{
"department" : "b","employee" ["c"]
}
]
解决方法
您可以执行以下操作,
var arraJson = [
{
"name" : "a","department": "a"
},{
"name" : "b",{
"name" : "c","department": "b"
}]
res = arraJson.reduce((prev,curr) => {
let index = prev.findIndex(item => item.department === curr.department);
if(index > -1) {
prev[index].employee.push(curr.name);
} else {
prev.push({ 'department': curr.department,'employee': [curr.name] });
}
return prev;
},[]);
console.log(res);