How to count object values using javascript -
i have object arrays inside. arrays grouped 'sku'. , should count object values inside grouped sku's. if there farbigkeit, proof or eindruck count them how apear , sum quan.
fiddle: https://jsfiddle.net/tokadmwn/2/
<pre id="result"></pre>
javascript:
var mydata = [ { sku: "9017wks43dp", quan: 100, farbigkeit: "a90zukos4599", proof: "a90zukos4499" }, { sku: "9017wks18dp", quan: 100 }, { sku: "9017was18dp", quan: 50, eindruck: "a90zukos4799" }, { sku: "9017was18dp", quan: 40, eindruck: "a90zukos4799", proof: "a90zukos4499" }, { sku: "9017wks43dp", quan: 200, farbigkeit:"a90zukos4699", proof: "a90zukos4499" }, { sku: "9017wks43dp", quan: 200, farbigkeit:"a90zukos4599" } ]; function groupby(propertyname, array) { var groupedelements = {}; for(var = 0; < array.length; i++) { var element = array[i]; var value = element[propertyname]; var quantity = element['quan']; var group = groupedelements[value]; if(group == undefined) { group = [element]; groupedelements[value] = group; } else { group.push(element); } } return groupedelements; } var result = groupby("sku", mydata); console.log(result); $("#result").html(json.stringify(result, null, 4));
without jquery:
function aggr(data) { var res={}; mydata.foreach(function(item){ res[item.sku]=res[item.sku]||{quan:0}; res[item.sku].quan+=1*item.quan; ["farbigkeit","proof","eindruck"].foreach(function(p) { res[item.sku][p]=(res[item.sku][p]?res[item.sku][p]:0)+(item[p]?1:0); }) }); return res; }
Comments
Post a Comment