gpt4 book ai didi

angularjs - 从多个 JSON 对象值中获取平均值

转载 作者:行者123 更新时间:2023-12-02 03:14:04 24 4
gpt4 key购买 nike

我有以下数据:

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”错误。

最佳答案

看看这个..

<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>

这是 fiddle .. https://jsfiddle.net/4t1teyk0/

检查您的控制台。

这是输出

enter image description here

关于angularjs - 从多个 JSON 对象值中获取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38097504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com