3

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?

4

2 回答 2

3

您需要使用parseInt()将字符串转换为数字。否则,+` 执行字符串连接而不是加法。

此外,您需要sum在循环外进行初始化。否则,您的总和每次都会被清除,并且您不会计算总数。

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);
    }
});
于 2015-01-29T03:20:43.103 回答
0

您在sum内部使用了一个局部变量$.each,该值在每次迭代时都会重新分配,并且您的变量bushels_per_daystring类型化的,所以 JS 只是将它的值与sum值连接起来

试试这个。它对我有用

于 2015-01-29T03:57:52.897 回答