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

Javascript 如何按子值将对象数组拆分为多个对象数组,javascript,arrays,object,split,underscore.js,Javascript,Arrays,Object,Split,Underscore.js,我需要按数组的objects子值(type)拆分数组。 假设我有以下数组: [ {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 :"custo

我需要按数组的objects子值(type)拆分数组。 假设我有以下数组:

[
  {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: { ... }}
  ]
 }, 
]
下划线在我的项目中可用。可以包括任何其他帮助程序库

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

您可以使用:

您可以使用:


这将返回您想要的内容:

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

这将返回您想要的内容:

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

纯Javascript的解决方案,带有组的临时对象

var数组=[{id:1,名称:“John”,信息:{type:“employee”},{id:2,名称:“Charles”,信息:{type:“employee”},{id:3,名称:“Emma”,信息:{type:“ceo”},{id:4,名称:“Jane”,信息:{type:“customer”},
结果=[];
array.forEach(函数(a){
var type=a.information.type;
如果(!此[类型]){
此[type]={type:type,persons:[]};
结果.推送(此[类型]);
}
此[type].persons.push({id:a.id,name:a.name});
}, {});

document.write(“”+JSON.stringify(结果,0,4)+“”)纯Javascript的解决方案,带有组的临时对象

var数组=[{id:1,名称:“John”,信息:{type:“employee”},{id:2,名称:“Charles”,信息:{type:“employee”},{id:3,名称:“Emma”,信息:{type:“ceo”},{id:4,名称:“Jane”,信息:{type:“customer”},
结果=[];
array.forEach(函数(a){
var type=a.information.type;
如果(!此[类型]){
此[type]={type:type,persons:[]};
结果.推送(此[类型]);
}
此[type].persons.push({id:a.id,name:a.name});
}, {});

document.write(“”+JSON.stringify(结果,0,4)+“”)请添加您的解决方案。请添加您的解决方案。