按标识符、JavaScript 对组数组使用 reduce

问题描述

我有一个应该放出来的对象

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);