2017-07-28 65 views
0

我有一個內部數組的對象。這個數組由'sku'分組。 現在我應該計算分組sku中的對象值。因此,如果有遠見,證據或eindruck數他們多久他們apear並且總結quan。如何使用javascript計算對象值

小提琴: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 i = 0; i < 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)); 
+0

預期結果是什麼? – Val

+0

你爲什麼要顯示'groupBy'? –

+0

sku –

回答

0

沒有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; 
} 
0

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" } 
 
]; 
 

 
var groupedData = myData.reduce(function(result, current) { 
 
    result[current.sku] = result[current.sku] || []; 
 
    result[current.sku].push(current); 
 
    return result; 
 
}, {}); 
 

 
for (var key in groupedData){ 
 
    groupedData[key] = groupedData[key].length; 
 
} 
 

 
console.log(groupedData);