使用JavaScript映射和减少JSON对象

前端之家收集整理的这篇文章主要介绍了使用JavaScript映射和减少JSON对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑下面的这个 JSON对象:
{
   "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
      },"gdp_growth__avg":-5.04693945214571,"geo__name":"russia","gdp_growth__avg":-0.0622142217811472,"geo__name":"botswana","gdp_growth__avg":14.2407063986337,"time":1992
      },"gdp_growth__avg":-14.5310737731921,"gdp_growth__avg":3.55494453739944,"gdp_growth__avg":13.9643147001603,"time":1993
      },"gdp_growth__avg":-8.66854034194856,"gdp_growth__avg":2.74204850437989,"gdp_growth__avg":4.04272516401846,"time":1994
      },"gdp_growth__avg":13.0806818010789,"gdp_growth__avg":-12.5697559787493,"gdp_growth__avg":10.9249803004994,"time":1995
      },"gdp_growth__avg":-4.14352840666389,"gdp_growth__avg":2.71655384149574,"gdp_growth__avg":10.0085233990531,"time":1996
      },"gdp_growth__avg":3.79848988541973,"time":1996
      }
]
}

我想Map和Reduce并生成一个新对象,其中包含上述JSON中所有国家的GDP增长总和,可能看起来大致如下:

{  
  {
     "gdp_growth__avg":46.23,},{
     "gdp_growth__avg":16.23,{
     "gdp_growth__avg":36.23,{
     "gdp_growth__avg":26.23,"time":1991
  }
 }

我看过mapreduce,我不确定如何最好地继续.

我认为这样的事情可能会朝着正确的方向发展,但似乎并没有像我期望的那样:

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完成.有什么建议?提前致谢.

解决方法

试试这个:
var data = { cells:[...] };

var r = data.cells.reduce(function(pv,cv) {
    if ( pv[cv.geo__name] ) {
        pv[cv.geo__name] += cv.gdp_growth__avg;
    } else {
        pv[cv.geo__name] = cv.gdp_growth__avg;
    }
    return pv;
},{});

console.log(r);

输出示例:

{ 
      'united states of america': 18.76051995774611,'china': 71.39814330096999,'russia': -36.291297610751,'botswana': -8.730754563729707 
   }
原文链接:https://www.f2er.com/js/158098.html

猜你在找的JavaScript相关文章