[英]how to split array of objects into multiple array of objects by subvalue
我需要按其對象子值(類型)拆分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"}}
]
我想按信息類型拆分對象,所以最終結果如下所示:
[
{
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]}))
您可以使用underscore.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; });
使用純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.