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

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

本文关键字:数组 对象 拆分 何按      更新时间:2024-05-11

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

[
  {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"}}
]

我想按信息分割对象。键入,这样我的最终结果看起来像:

[
 {
  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: { ... }}
  ]
 }, 
]

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

当然,我可以循环遍历数组并实现自己的逻辑,但我正在寻找更干净的解决方案。

这会返回您想要的:

_.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>');

您可以使用undercore.js:的groupBy函数

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