按年份对Json数据进行分组,以便使用amchart创建堆积的条形图

时间:2019-04-22 14:33:40

标签: javascript json angularjs amcharts

我正在使用amchart为dataProvider准备数据,以创建https://www.amcharts.com/demos-v3/stacked-column-chart-v3/这样的堆积柱形图, 我对服务的响应如下所示,我想按年份对数据进行分组 所以我必须更改json数据:

"Annee": "2018 / 2019",
"Chargeniv1": "Centre",
"MensuelCout": 123
},
{
"Annee": "2018 / 2019",
"Chargeniv1": "Main",
"MensuelCout": 456
},
{
"Annee": "2018 / 2019",
"Chargeniv1": "principaux",
"MensuelCout": 789
},
{
"Annee": "2017 / 2018",
"Chargeniv1": "structure",
"MensuelCout": 101
},
{
"Annee": "2017 / 2018",
"Chargeniv1": "principaux",
"MensuelCout": 629
},
{
"Annee": "2017 / 2018",
"Chargeniv1": "Main",
"MensuelCout": 985
}]

以此

[{
  "annee":"2018 / 2019"
  "Centre": 637612,
  "Main": 456,
  "principaux": 789,
    },
 {
  "annee":"2017 / 2018"
  "Centre": 101,
  "principaux": 629,
  "Main": 987,
}]

感谢您的关注

2 个答案:

答案 0 :(得分:1)

您可以使用函数reduce来按年份对对象进行分组,而函数Object.values可以用于提取已分组的对象。

let array = [ { "Annee": "2018 / 2019", "Chargeniv1": "Centre", "MensuelCout": 123 }, { "Annee": "2018 / 2019", "Chargeniv1": "Main", "MensuelCout": 456 }, { "Annee": "2018 / 2019", "Chargeniv1": "principaux", "MensuelCout": 789 }, { "Annee": "2017 / 2018", "Chargeniv1": "structure", "MensuelCout": 101 }, { "Annee": "2017 / 2018", "Chargeniv1": "principaux", "MensuelCout": 629 }, { "Annee": "2017 / 2018", "Chargeniv1": "Main", "MensuelCout": 985 }];
let result = Object.values(array.reduce((a, {Annee, Chargeniv1, MensuelCout}) => {
  a[Annee] = a[Annee] || (a[Annee] = {Annee});
  a[Annee][Chargeniv1] = (a[Annee][Chargeniv1] || 0) + MensuelCout;
  return a;
}, {}));

console.log(result);
.as-console-wrapper { min-height: 100%; }

答案 1 :(得分:1)

我将在特定年份使用过滤器功能和新设置。

您的json响应:

    let data = [
          {
            Annee: "2018 / 2019",
            Chargeniv1: "Centre",
            MensuelCout: 123
          }...
        ];

获取所有年份:

var years = new Set();
data.forEach((element, index) => {
  years.add(element.Annee);
});

使用数据创建一个新数组并根据需要进行组织。

var newData = [];
uniqueYears.forEach((year, index) => {
  newData.push({ year: year, cities: data.filter(y => y.Annee === year) });
});