我有一个使用 jQuery CSV ( https://github.com/evanplaice/jquery-csv/ ) 转换为 jQuery 对象的 csv 文件。

这是代码:

    $.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);
    });

我需要按对象中的键来总结值。具体来说,我需要按公司将 busels_per_day 值相加。

对象格式如下:
    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
    ]

这不起作用:
    $.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);
        }
    });

它只返回每个公司的前导零的值:

0145

0120

060

等等。

我怎样才能做到这一点?

最佳答案

您需要使用 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);
    }
});

关于jquery - 按键对 jQuery 对象中的值求和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28206415/

10-12 00:00
查看更多