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));
預期結果是什麼? – Val
你爲什麼要顯示'groupBy'? –
sku –