Sum values in jQuery object by key

六月ゝ 毕业季﹏ 提交于 2019-12-07 17:07:11

问题


I have a csv file converted to a jQuery object using jQuery CSV (https://github.com/evanplaice/jquery-csv/).

Here is the code for that:

    $.ajax({
        type: "GET",
        url: "/path/myfile.csv",
        dataType: "text",
        success: function(data) {
        // once loaded, parse the file and split out into data objects
        // we are using jQuery CSV to do this (https://github.com/evanplaice/jquery-csv/)

        var data = $.csv.toObjects(data);
    });

I need to sum up values by key in the object. Specifically, I need to add up the bushels_per_day values by company.

The object format is like so:

    var data = [
        "0":{
            beans: "",
            bushels_per_day: "145",
            latitude: "34.6059253",
            longitude: "-86.9833417",
            meal: "",
            oil: "",
            plant_city: "Decatur",
            plant_company: "AGP",
            plant_state: "AL",
            processor_downtime: "",
        },
        // ... more objects
    ]

This isn't working:

    $.each(data, function(index, value) { 
        var capacity = value.bushels_per_day;
        var company = value.plant_company.replace(/\W+/g, '_').toLowerCase();
        var sum = 0;
        if (company == 'agp') {
            sum += capacity;
            console.log(sum);
        }
    });

It just returns the value for each with a leading zero by company:

0145

0120

060

etc.

How can I do this?


回答1:


You need to use parseInt() to convert the strings to numbers. Otherwise,+` does string concatenation instead of addition.

Also, you need to initialize sum outside the loop. Otherwise, your sum gets cleared every time, and you're not calculating a total.

var sum = 0;
$.each(data, function(index, value) { 
    var capacity = parseInt(value.bushels_per_day, 10);
    var company = value.plant_company.replace(/\W+/g, '_').toLowerCase();
    if (company == 'agp') {
        sum += capacity;
        console.log(sum);
    }
});



回答2:


You are using a local variable sum inside $.each, which value is reassigned at every iteration, and your variable bushels_per_day is stringtyped, so JS just concatenate it's value with sum value

Try this. It worked for me



来源:https://stackoverflow.com/questions/28206415/sum-values-in-jquery-object-by-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!