2016-12-12 5 views
2

Was ist der beste Weg ist, um ein Objekt Array von unterschiedlicher Länge, die so aussieht zusammenzufassen:Sum Objektarray von unterschiedlicher Länge von Wert

data = [{"category":"category1","months":{"1":34,"2":67,"3":29,...} 
{"category":"category2","months":{"1":34,"2":627,"3":292,...} 
{"category":"category3","months":{"1":46,"2":665,"3":129,...} 
{"category":"category4","months":{"1":624,"2":667,"3":629,...} 
{"category":"category5","months":{"1":32,"2":637,"3":299,...} 
}] 

Ich möchte im Grunde Gruppe von Monat und Summe und zuweisen, die zu einem Gesamtkategorie So würde ich ein neues Objekt erhalten, das wie folgt aussieht, dass ich mein Datenobjekt schieben würde:

{"category":"total","months":{"1":770,"2":2663,"3":1378,...} 

ich würde am Ende:

data = [{"category":"category1","months":{"1":34,"2":67,"3":29,...} 
{"category":"category2","months":{"1":34,"2":627,"3":292,...} 
{"category":"category3","months":{"1":46,"2":665,"3":129,...} 
{"category":"category4","months":{"1":624,"2":667,"3":629,...} 
{"category":"category5","months":{"1":32,"2":637,"3":299,...} 
{"category":"total","months":{"1":770,"2":2663,"3":1378,...} 
}] 

Antwort

1
let data = [ 
{"category":"category1","months":{"1":34,"2":67,"3":29}}, 
{"category":"category2","months":{"1":34,"2":627,"3":292}}, 
{"category":"category3","months":{"1":46,"2":665,"3":129}}, 
{"category":"category4","months":{"1":624,"2":667,"3":629}}, 
{"category":"category5","months":{"1":32,"2":637,"3":299}}, 
]; 

let total = {"category":"total","months":{}}; 

data.forEach(category => { 
     for(let prop in category.months){ 
      if (total.months[prop]){ 
      total.months[prop] += category.months[prop]; 
      } 
      else{ 
      total.months[prop] = category.months[prop]; 
      } 
     } 
}); 

data.push(total); 
1

Verwenden Array.prototype.reduce und ein hash table bekommen die ' total 'Objekt und schiebe es später wieder auf die Daten, um die gewünschte Datenstruktur zu erhalten.

Siehe Demo unter:

var data=[{"category":"category1","months":{"1":34,"2":67,"3":29}},{"category":"category2","months":{"1":34,"2":627,"3":292}},{"category":"category3","months":{"1":46,"2":665,"3":129}},{"category":"category4","months":{"1":624,"2":667,"3":629}},{"category":"category5","months":{"1":32,"2":637,"3":299}}] 
 

 
var result = data.reduce(function(hash){ 
 
    return function(p,c){ 
 
    Object.keys(c.months).forEach(function(e){ 
 
     if(e in p.months) { 
 
     p.months[e] += c.months[e]; 
 
     } else { 
 
     p.months[e] = +c.months[e]; 
 
     } 
 
    }); 
 
    return p; 
 
    } 
 
}(Object.create(null)), {category:"total",months:{}}); 
 

 
console.log(result); 
 

 
// now push this to data 
 
data.push(result); 
 

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

Verwandte Themen