如何按子值将对象数组拆分为多个对象数组

how to split array of objects into multiple array of objects by subvalue

我需要按对象子值(类型)拆分数组。 假设我有以下数组:

[
  {id:1,name:"John",information: { type :"employee"}},
  {id:2,name:"Charles",information: { type :"employee"}},
  {id:3,name:"Emma",information: { type :"ceo"}},
  {id:4,name:"Jane",information: { type :"customer"}}
]

我想将对象拆分 information.type 所以我的最终结果如下:

[
 {
  type:"employee",
  persons:
  [
   {id:1,name:"John",information: { ... }},
   {id:2,name:"Charles",information: { ... }
  ]
 },
{
  type:"ceo",
  persons:
  [
   {id:3,name:"Emma",information: { ... }}
  ]
 },
{
  type:"customer",
  persons:
  [
   {id:4,name:"Jane",information: { ... }}
  ]
 }, 
]

Underscore 在我的项目中可用。可以包含任何其他帮助程序库。

当然我可以遍历数组并实现我自己的逻辑,但我一直在寻找更简洁的解决方案。

您可以使用 groupBy function of underscore.js:

var empList = [
{id:1,name:"John",information: { type :"employee"}},
  {id:2,name:"Charles",information: { type :"employee"}},
  {id:3,name:"Emma",information: { type :"ceo"}},
  {id:4,name:"Jane",information: { type :"customer"}}
];
_.groupBy(empList, function(emp){ return emp.information.type; });

这returns正是您想要的:

_.pairs(_.groupBy(originalArray, v => v.information.type)).map(p => ({type: p[0], persons: p[1]}))

一个简单的解决方案 Javascript,其中包含一个用于群组的临时对象。

var array = [{ id: 1, name: "John", information: { type: "employee" } }, { id: 2, name: "Charles", information: { type: "employee" } }, { id: 3, name: "Emma", information: { type: "ceo" } }, { id: 4, name: "Jane", information: { type: "customer" } }],
    result = [];

array.forEach(function (a) {
    var type = a.information.type;
    if (!this[type]) {
        this[type] = { type: type, persons: [] };
        result.push(this[type]);
    }
    this[type].persons.push({ id: a.id, name: a.name });
}, {});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');