我有以下数据的数据:
var v = {
"2015-09-23":[
{"AllConversions":"0.1","AverageCpc":"0.01","AverageCpm":"0.02","AveragePosition":"8.3",Id:1},
{"AllConversions":"0.0","AverageCpc":"0.00","AverageCpm":"0.00","AveragePosition":"9.0",Id:1}
],
"2015-09-18":[
{"AllConversions":"0.1","AverageCpc":"77.14","AverageCpm":"239.57","AveragePosition":"7.7",Id:1},
{"AllConversions":"0.0","AverageCpc":"39.97","AverageCpm":"703.91","AveragePosition":"3.8",Id:1},
{"AllConversions":"0.0","AverageCpc":"20.40","AverageCpm":"381.36","AveragePosition":"4.3",Id:1}
]
};
var columns = [
"AllConversions",
"AverageCpc",
"AverageCpm",
"AveragePosition"
];
我想返回以下对象,它是没有Id的所有字段的总和:
{
"2015-09-23": [
{"AllConversions":"0.1","AverageCpc":"0.01","AverageCpm":"0.02","AveragePosition":"17.3",Id:1}
],
"2015-09-18": [
{"AllConversions":"0.1","AverageCpc":"137.51","AverageCpm":"1324.84","AveragePosition":"15.8",Id:1}
]
}
我使用了下面的内容尝试了这个代码:
_.each(columns,function(item){
var out = _(groups).map(function (g, key) {
return {
Date: key,
item: _(g).reduce(function (m, x) { return m + x.item; }, 0)
}
});
});
但是在运行代码时出现'NaN'错误。
答案 0 :(得分:1)
检查出来..
<html>
<head>
<script>
var v={
"2015-09-23":[
{"AllConversions":"0.1","AverageCpc":"0.01","AverageCpm":"0.02","AveragePosition":"8.3",Id:1},
{"AllConversions":"0.0","AverageCpc":"0.00","AverageCpm":"0.00","AveragePosition":"9.0",Id:1}
],
"2015-09-18":[
{"AllConversions":"0.1","AverageCpc":"77.14","AverageCpm":"239.57","AveragePosition":"7.7",Id:1},
{"AllConversions":"0.0","AverageCpc":"39.97","AverageCpm":"703.91","AveragePosition":"3.8",Id:1},
{"AllConversions":"0.0","AverageCpc":"20.40","AverageCpm":"381.36","AveragePosition":"4.3",Id:1}
]};
var columns=[
"AllConversions","AverageCpc","AverageCpm","AveragePosition"
];
var output = {};
var smallOutput = {};
var tempDate = [];
for(var i in v){
var temp = 0;
for(var j = 0; j < columns.length ; j++){
for(var k = 0 ; k < v[i].length; k++) temp += parseFloat(v[i][k][columns[j]]);
smallOutput[columns[j]] = temp ;
temp=0;
}
output[[i]] = smallOutput;
}
console.log(output);
</script>
</head>
<body>
</body>
</html>
这是小提琴.. https://jsfiddle.net/4t1teyk0/
检查您的控制台。
这是输出