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

时间:2016-04-12 16:01:48

标签: javascript arrays object split underscore.js

我需要通过对象subvalue(type)拆分一个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"}}
]

我希望通过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: { ... }}
  ]
 }, 
]

我的项目提供下划线。可以包括任何其他帮助程序库。

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

2 个答案:

答案 0 :(得分:0)

您可以使用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; });

答案 1 :(得分:0)

普通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>');