2016-04-12 29 views
0

Nesneleri alt değerlerine (türüne) göre bir Array bölmem gerekiyor. ı dizinin aşağıdakilere sahip varsayalım:Nesnelerin çok sayıda nesnelere nasıl eşleştirileceği

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

ve nihai sonucudur benziyor yüzden information.type nesneyi bölmek istiyorum:

[ 
{ 
    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 benim Projesi mevcuttur. Diğer yardımcı kütüphaneler dahil edilebilir.

Elbette diziden geçebilir ve kendi mantığımı uygulayabilirim, ama daha temiz bir çözüm arıyordum.

+0

çözümünüzü ekleyin. –

cevap

3

: gruplar için geçici bir nesne ile düz JavaScript

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

bu, saf bir parlaklık. teşekkürler @ 4lejandrito – ManuKaracho

0

Şunları kullanabilirsiniz groupBy function of underscore.js:

Bu tam olarak ne istediğinizi döner
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; }); 
0

bir çözüm.

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