javascript - Sum object of array by same element -
var data = [ {id: 1, quantity: 10, category: 'a'}, {id: 2, quantity: 20, category: 'b'}, {id: 1, quantity: 30, category: 'a'}, {id: 1, quantity: 30, category: 'z'}, {id: 2, quantity: 40, category: 'd'} ]; var totalpertype = {}; (var = 0, len = data.length; < len; ++i) { totalpertype[data[i].id] = totalpertype[data[i].id] || 0; totalpertype[data[i].id] += data[i].quantity; } var out = _.map(totalpertype, function (id, quantity) { return {'id': id, 'quantity': quantity}; }); console.log(out);
my code sums quantity objects same id. returns
[ {id:1, quantity:70}, {id:2, quantity:60} ]
how sum objects based on both id , category?
for example, need output this:
[ {id:1, quantity:40, category:a}, {id:1, quantity:30, category:z}, {id:2, quantity:20, category:b}, {id:, quantity:40, category:d} ]
i'd answer both plain javascript , underscore.
using vanilla js.
var tmp = {} data.foreach(function (item) { var tempkey = item.id + item.category; if (!tmp.hasownproperty(tempkey)) { tmp[tempkey] = item; } else { tmp[tempkey].quantity += item.quantity; } }); var results = object.keys(tmp).map(function(key){ return tmp[key]; });
note change objects in original data. need copy item
when adding tmp
object if unwanted
var data = [ {id: 1, quantity: 10, category: 'a'}, {id: 2, quantity: 20, category: 'b'}, {id: 1, quantity: 30, category: 'a'}, {id: 1, quantity: 30, category: 'z'}, {id: 2, quantity: 40, category: 'd'} ]; var tmp = {} data.foreach(function (item) { var tempkey = item.id + item.category; if (!tmp.hasownproperty(tempkey)) { tmp[tempkey] = item; } else { tmp[tempkey].quantity += item.quantity } }); var results = object.keys(tmp).map(function(key){ return tmp[key]; }); document.body.innerhtml ='<pre>' + json.stringify(results,null,4) +'</pre>';
Comments
Post a Comment