我有一个使用jQuery CSV文件(https://github.com/evanplaice/jquery-csv)转换为jQuery对象。
这是代码:
$.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://code.google.com/p/jquery-csv/)
var data = $.csv.toObjects(data);
});
我正在按公司将bushels_per_day值相加,并希望重构我的代码以使其更紧凑。
使用这个答案:按键对 jQuery 对象中的值求和,我能够使用 $.each() 循环访问;
对象格式如下所示:
var data = [
"0":{
bushels_per_day: "145",
plant_city: "Decatur",
plant_company: "AGP",
},
"1":{
bushels_per_day: "125",
plant_city: "Cedar Rapids",
plant_company: "AGP",
},
"2":{
bushels_per_day: "345",
plant_city: "Ralston",
plant_company: "AGP",
},
"3":{
bushels_per_day: "55",
plant_city: "Dawson",
plant_company: "ADM",
},
"4":{
bushels_per_day: "55",
plant_city: "Dawson",
plant_company: "ADM",
},
// ... more objects
]
下面是 $.each() 循环:
var sumADM = 0;
var sumAGP = 0;
// var for each company
$.each(data, function (index, value) {
var capacity = parseInt(value.bushels_per_day, 10);
var company = value.plant_company.replace(/W+/g, '_').toLowerCase();
if (company == 'adm') {
sumADM += capacity;
}
if (company == 'agp') {
sumAGP += capacity;
}
// ... and so on for each company
});
console.log(sumADM, sumAGP); // and so on.
这有效,但是我如何重构它,以便我不需要每个公司的 sum 变量和 if 语句?目前,sum 变量和 console.log() 必须在循环外部才能返回正确的总计。
有没有更好、更紧凑的方法可以做到这一点?
您可以将对象上的总和作为属性:
var sums = {
ADM: 0,
AGP: 0
};
$.each(data, function (index, value) {
var capacity = parseInt(value.bushels_per_day, 10);
var company = value.plant_company.replace(/W+/g, '_').toUpperCase(); // Note change here
sums[company] += capacity;
});
console.log(sums.ADM, sums.AGP); // and so on.
或者循环输出它们:
Object.keys(sums).forEach(function(company) {
console.log(sums[company]);
});
你甚至可以做懒惰的初始化,如果公司不同:
var sums = {};
$.each(data, function (index, value) {
var capacity = parseInt(value.bushels_per_day, 10);
var company = value.plant_company.replace(/W+/g, '_').toUpperCase();
sums[company] = (sums[company] || 0) + capacity;
});
Object.keys(sums).forEach(function(company) {
console.log(sums[company]);
});
sums[company] = (sums[company] || 0) + capacity;
线的工作方式是,如果我们以前没有见过那家公司,sums[company]
就会undefined
.由于undefined
是假的,JavaScript 奇特强大的||
运算符将采用右操作数值(0
)作为其结果。如果我们以前看过company
并且sums[company]
0
,这也是正确的,但这没关系,0
是0
.所有其他值(1
等)都是真值,因此sum[company] || 0
将是1
这样的(左操作数的值)。
旁注:请注意,我在公司字符串上使用toUpperCase
而不是toLowerCase
,因此它们与属性匹配。