我想用JavaScript实现这一目标。
[{ "employeeName":"emp1", "Deaprtment":"dept1"},
{ "employeeName":"emp2", "Deaprtment":"dept1"}
]
到
{"dept1":{"emp1","emp2"}}
请使用JavaScript建议可能的解决方案。
答案 0 :(得分:1)
您给定的预期输出无效,但您可以获得这样的输出。
var arr = [{ "employeeName":"emp1", "Deaprtment":"dept1"},
{ "employeeName":"emp2", "Deaprtment":"dept1"}
];
var newObj = {};
for(let i in arr){
if(arr[i].Deaprtment in newObj){
newObj[arr[i].Deaprtment].push(arr[i].employeeName);
}else{
newObj[arr[i].Deaprtment] = [arr[i].employeeName];
}
}
console.log(newObj);

答案 1 :(得分:0)
如果您将输出视为{"dept1":["emp1","emp2"]}
,请使用reduce
var output = arr.reduce( ( a, b ) => (
a[ b.Deaprtment ] = a[ b.Deaprtment ] || [],
a[ b.Deaprtment ].push( b.employeeName ),
a ) ,{} );