简体   繁体   English

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

[英]how to split array of objects into multiple array of objects by subvalue

I need to split an Array by its objects subvalue (type). 我需要按其对象子值(类型)拆分Array。 Let's assume I have following 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"}}
]

and I want to split the object by information.type so my final result looks like: 我想按信息类型拆分对象,所以最终结果如下所示:

[
 {
  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 is available at my Project. 下划线在我的项目中可用。 Any other helper library could be included. 可以包括任何其他帮助程序库。

Of course I could loop through the array and implement my own logic, but i was looking for cleaner solution. 当然,我可以遍历数组并实现自己的逻辑,但我一直在寻找更清洁的解决方案。

这恰好返回您想要的:

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

You could use the groupBy function of underscore.js : 您可以使用underscore.jsgroupBy函数

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

A solution in plain Javascript with a temporary object for the groups. 使用纯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>'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM