{"name": "John", "age": 30, "city": "New York"}
考虑下面的 JSON 对象:{"name": "John", "age": 30, "city": "New York"}。
考虑下面的 JSON 对象:{"name": "John", "age": 30, "city": "New York"}。
{
"cells":[
{
"count":"1",
"gdp_growth__avg":1.90575802503285,
"geo__name":"united states of america",
"time":1990
},
{
"count":"1",
"gdp_growth__avg":9.17893670154459,
"geo__name":"china",
"time":1991
},
{
"count":"1",
"gdp_growth__avg":-5.04693945214571,
"geo__name":"russia",
"time":1991
},
{
"count":"1",
"gdp_growth__avg":-0.0622142217811472,
"geo__name":"botswana",
"time":1991
},
{
"count":"1",
"gdp_growth__avg":14.2407063986337,
"geo__name":"china",
"time":1992
},
{
"count":"1",
"gdp_growth__avg":-14.5310737731921,
"geo__name":"russia",
"time":1992
},
{
"count":"1",
"gdp_growth__avg":3.55494453739944,
"geo__name":"united states of america",
"time":1992
},
{
"count":"1",
"gdp_growth__avg":13.9643147001603,
"geo__name":"china",
"time":1993
},
{
"count":"1",
"gdp_growth__avg":-8.66854034194856,
"geo__name":"botswana",
"time":1993
},
{
"count":"1",
"gdp_growth__avg":2.74204850437989,
"geo__name":"united states of america",
"time":1993
},
{
"count":"1",
"gdp_growth__avg":4.04272516401846,
"geo__name":"united states of america",
"time":1994
},
{
"count":"1",
"gdp_growth__avg":13.0806818010789,
"geo__name":"china",
"time":1994
},
{
"count":"1",
"gdp_growth__avg":-12.5697559787493,
"geo__name":"russia",
"time":1994
},
{
"count":"1",
"gdp_growth__avg":10.9249803004994,
"geo__name":"china",
"time":1995
},
{
"count":"1",
"gdp_growth__avg":-4.14352840666389,
"geo__name":"russia",
"time":1995
},
{
"count":"1",
"gdp_growth__avg":2.71655384149574,
"geo__name":"united states of america",
"time":1995
},
{
"count":"1",
"gdp_growth__avg":10.0085233990531,
"geo__name":"china",
"time":1996
},
{
"count":"1",
"gdp_growth__avg":3.79848988541973,
"geo__name":"united states of america",
"time":1996
}
]
}
我想使用Map和Reduce生成一个新对象,其中包含上述JSON中所有国家的GDP增长总和,大致如下:
{
{
"gdp_growth__avg":46.23,
"geo__name":"united states of america",
},
{
"gdp_growth__avg":16.23,
"geo__name":"china",
},
{
"gdp_growth__avg":36.23,
"geo__name":"russia",
},
{
"gdp_growth__avg":26.23,
"geo__name":"botswana",
"time":1991
}
}
我已经查看了 map 和 reduce,但不确定如何最好地进行操作。
我认为这样做可能朝着正确的方向前进,但似乎并没有做到我期望的效果:
var arr = [{x:1},{x:2},{x:4}];
arr.reduce(function (a, b) {
return {x: a.x + b.x};
});
console.log(arr); //Outputs that same initial array
虽然我知道这可能更好、更容易在服务器端完成,但我想知道是否可以在客户端使用JavaScript来实现我想要做的事情。有什么建议吗?提前感谢。
console.log(arr.reduce(…))
。reduce
方法不会改变数组(甚至不会重新赋值给变量),它只是返回一个值。 - Bergimap
和reduce
也可以在服务器端使用。 可能您的服务器可以运行它。 在js或python中最方便(是否有基于python的服务器?) - sqykly