按键求和jQuery对象中的值 [英] Sum values in jQuery object by key
问题描述
我有一个使用jQuery CSV转换为jQuery对象的csv文件( https://github.com /evanplaice/jquery-csv/).
I have a csv file converted to a jQuery object using jQuery CSV (https://github.com/evanplaice/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值相加.
I need to sum up values by key in the object. Specifically, I need to add up the bushels_per_day values by company.
对象格式如下:
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);
}
});
它只返回公司前导零的每个值:
It just returns the value for each with a leading zero by company:
0145
0120
060
等
我该怎么做?
推荐答案
您需要使用parseInt()
将字符串转换为数字.否则,,
+`会进行字符串连接而不是加法.
You need to use parseInt()
to convert the strings to numbers. Otherwise,
+` does string concatenation instead of addition.
此外,您需要在循环外初始化sum
.否则,您的总和每次都会被清除,并且您不是在计算总和.
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);
}
});
这篇关于按键求和jQuery对象中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!