根据值对数组对象进行分组

时间:2018-10-10 02:09:20

标签: javascript arrays json

所以我有一个具有这种结构的数组对象变量

var array_obj = [
   {
      Gooble: 240,
      year: 2018
   },
   {
      Koolle: 220,
      year: 2018
   }
    {
      Zooae: 220,
      year: 2015
   }
];

但是我想遵循这种结构https://www.amcharts.com/demos/stacked-column-chart

所以现在应该是

    var array_obj = [
       {
          Gooble: 240,
          Koolle: 220,
          year: 2018
       },
       {
          Zooae: 220,
          year: 2015
       }
    ];

我一直在尝试通过此循环执行此操作,但似乎无法正确执行。

for(var i in array_obj){
   if(array_obj[i].year == array_obj[i].year){
      # Push here
   }
}

2 个答案:

答案 0 :(得分:1)

使用reduce创建按年份索引的对象的对象,如果不存在则先创建子对象,然后遍历非年份属性并分配给子对象上的适当键。 / p>

还要确保更正您的输入array_obj-所有数组项都需要用逗号分隔,以使语法有效:

var array_obj = [
   {
      Gooble: 240,
      year: 2018
   },
   {
      Koolle: 220,
      year: 2018
   },
    {
      Zooae: 220,
      year: 2015
   }
];
const outputByYear = array_obj.reduce((a, { year, ...rest }) => {
  if (!a[year]) a[year] = { year };
  Object.entries(rest).forEach(([key, val]) => {
    a[year][key] = val;
  });
  return a;
}, {});
console.log(Object.values(outputByYear));

答案 1 :(得分:1)

另一种解决方案是构建一个以年为键,合并数据为值的对象:

var array_obj = [{
    Gooble: 240,
    year: 2018
  },
  {
    Koolle: 220,
    year: 2018
  },
  {
    Zooae: 220,
    year: 2015
  }
];

let yearBuckets = {};
array_obj.forEach(b => {
  if (b.year in yearBuckets) Object.assign(yearBuckets[b.year], b);
  else yearBuckets[b.year] = b;
});
console.log(Object.values(yearBuckets));