如何按值对对象数组进行分组

时间:2019-05-01 09:21:28

标签: javascript arrays group-by

我正在为自己的组件之一创建数据集, 当前数据是

    [ 
        {name  : "John" , id : "123"} ,
        {name  : "Josh" , id : "1234"},
        {name  : "Charlie" , id : "1234253"},
        {name  : "Charles" , id : "123345"}
    ]

想像这样分组

    {
        C : [{name:"Charlie",id:"1234253"},{name:"Charles",id:"123345"}],
        J : [{name:"John",id:"123"},{name:"Josh",id:"1234"}]
    }

2 个答案:

答案 0 :(得分:2)

您可以像这样使用reduce

var data =  [ 
        {name  : "John" , id : "123"} ,
        {name  : "Josh" , id : "1234"},
        {name  : "Charlie" , id : "1234253"},
        {name  : "Charles" , id : "123345"}
    ];
    
let result = data.reduce((r, e) => {
  
  let group = e.name[0];
 
  if(!r[group]) r[group] =  [e]
  
  else r[group].push(e);
  
  return r;
}, {})

console.log(result);

答案 1 :(得分:0)

您要检查输入数组中的所有对象,然后将其推入由对象名称的首字母标识的数组。

var input = [{
    name: "John",
    id: "123"
  },
  {
    name: "Josh",
    id: "1234"
  },
  {
    name: "Charlie",
    id: "1234253"
  },
  {
    name: "Charles",
    id: "123345"
  }
];
var result = {};

input.forEach(x => !!result[x.name[0]] ? result[x.name[0]].push(x) : result[x.name[0]] = [x]);
console.log(result);