我在字典中有一个javascript对象,如下所示:
{ date: "2010/01",
San_Francisco201001: 1,
San_Francisco201002: 2,
San_Francisco201003: 3,
},
{ date: "2010/02",
San_Francisco201001: 0,
San_Francisco201002: 1,
San_Francisco201003: 2,
}
想找到
{ date: "2010/01", sum: 6, ), { date: "2010/02", sum: 3, )
它有点棘手,因为属性名称是任意的。有任何线索如何去做?
感谢。
答案 0 :(得分:3)
这不是一个对象,即两个对象。我假设你把它们放在一个数组中。然后,您可以遍历数组,并遍历每个对象中的属性:
var result = [];
for (var i = 0; i < theArray.length; i++) {
var sum = 0;
for (var key in theArray[i]) {
if (key != 'date') {
sum += theArray[i][key];
}
}
result.push({ date: theArray[i].date, sum: sum });
}
答案 1 :(得分:0)
要查找特定date
值的总和,请使用如下的正文创建函数:
function getDate(date, arr) {
for(var i = arr.length; i--;) {
if(arr[i].date === date) {
var obj = { sum: 0; };
for(var prop in arr[i]) {
if(prop !== "date") {
obj.sum += arr[i][prop];
}
}
obj.date = obj.date;
return obj;
}
}
}
答案 2 :(得分:0)
这应该有效:
var data = [{ date: "2010/01", San_Francisco201001: 1, San_Francisco201002: 2, San_Francisco201003: 3, }, { date: "2010/02", San_Francisco201001: 0, San_Francisco201002: 1, San_Francisco201003: 2, }];
var result = [];
for(var i = 0; i < data.length; i++) {
var dateData = data[i];
var sum = 0;
for(var element in dateData) if(dateData.hasOwnProperty(element)) {
var elementData = dateData[element];
if(element != "date") {
sum += elementData;
}
}
result.push({date: dateData["date"], sum: sum});
}
答案 3 :(得分:0)
var data = [{ date: "2010/01", San_Francisco201001: 1, San_Francisco201002: 2, San_Francisco201003: 3 }, { date: "2010/02", San_Francisco201001: 0, San_Francisco201002: 1, San_Francisco201003: 2 }];
var out = {};
for(var row in data){
var stats = data[row];
var cnt = 0;
for(var itm in stats){
if(itm==="date")continue;
cnt += stats[itm];
}
out[stats["date"]] = cnt;
}
alert( out["2010/01"] );