如何使用javascript计算对象值

时间:2017-07-28 07:52:02

标签: javascript

我有一个带有数组的对象。该数组按'sku'分组。 现在我应该计算分组sku中的对象值。因此,如果有一个远程计算器,证据或者eindruck计算它们的频率,那么它们的数量和总和也是如此。

小提琴: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));

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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;
}