jquery - 按键求和 jQuery 对象中的值

标签 jquery each jquery-csv

我有一个使用 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);
    });

我需要按对象中的键求和值。具体来说,我需要按公司添加bushels_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/

相关文章:

javascript - 选中复选框上的图像和文本更改并还原

javascript - 无法隐藏/取消隐藏表单内的按钮

javascript - 为什么 jQueryeach() 函数中的全局变量会破坏我的翻转效果?

javascript - 引用错误 : CSV is not defined

javascript - 使用 jquery 处理 CSV

javascript - jQuery 合并/过滤器选择器

javascript - 删除子字符串和分解字符串的函数?

javascript - find() 用于多个结果

jQuery的每个元素,但只有第一个 parent ?

javascript - 从上传的 csv 数据创建数据表列定义