2016-09-29 2 views
0

ich eine Liste habenverschachtelte Liste Gruppierung groupBy mit unterstreichen

data = [{ 
     value1:[1,2], 
     value2:[{type:'A'}, {type:'B'}] 
    },{ 
     value1:[3,5], 
     value2:[{type:'B'}, {type:'B'}] 
    }] 

dieses Format meiner Liste und ich möchte diese Liste formatiert als

data = [ 
    {type:'A', value: [1,2]}, 
    {type:'B', value: [3,5]} 
] 
+0

Wo 4 kommt, ergeben sich auch ungültige Daten. –

Antwort

0

Wenn Sie das unten stehende Ergebnis

data = [ 
    {type:'A', value: [1,2]}, 
    {type:'B', value: [3,5]} 
] 
erwarten sind

das ist, was Sie wollen

data = [{ 
 
     value1:[1,2], 
 
     value2:[{type:'A'}, {type:'B'}] 
 
    },{ 
 
     value1:[3,5], 
 
     value2:[{type:'B'}, {type:'B'}] 
 
    }] 
 
    
 

 
data.forEach(function(item, index){ 
 
    var obj = {}; 
 
    obj.type = item.value2[0].type; 
 
    obj.value = item.value1; 
 
    console.log(obj); 
 
})

0

Sie können dies tun, mit zwei forEach() Schleifen und Objekt als thisArg Parameter in erster forEach() Schleife.

var data = [{ 
 
    value1: [1, 2], 
 
    value2: [{ 
 
    type: 'A' 
 
    }, { 
 
    type: 'B' 
 
    }] 
 
}, { 
 
    value1: [3, 5], 
 
    value2: [{ 
 
    type: 'B' 
 
    }, { 
 
    type: 'B' 
 
    }] 
 
}] 
 

 

 
var result = []; 
 
data.forEach(function(o, i) { 
 
    var that = this; 
 
    o.value2.forEach(function(t) { 
 
    if (!that[t.type]) { 
 
     that[t.type] = { 
 
     type: t.type, 
 
     value: [] 
 
     } 
 
     result.push(that[t.type]); 
 
    } 
 
    if (!that[i + '|' + t.type]) { 
 
     that[t.type].value = that[t.type].value.concat(o.value1); 
 
     that[i + '|' + t.type] = true; 
 
    } 
 
    }) 
 
}, {}) 
 

 
console.log(result)

0

Sie könnten einen Nachschlag für die Werte durchlaufen und haben.

var data = [{ value1: [1, 2], value2: [{ type: 'A' }, { type: 'B' }] }, { value1: [3, 5], value2: [{ type: 'B' }, { type: 'B' }] }], 
 
    grouped = []; 
 

 
data.forEach(function (a) { 
 
    a.value2.forEach(function (b) { 
 
     if (!this[b.type]) { 
 
      this[b.type] = { type: b.type, value: [] }; 
 
      grouped.push(this[b.type]); 
 
     } 
 
     a.value1.forEach(function (c) { 
 
      if (this[b.type].value.indexOf(c) < 0) { 
 
       this[b.type].value.push(c); 
 
      } 
 
     }, this); 
 
    }, this); 
 
}, Object.create(null)); 
 

 
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }