如何将json数组映射到图表的两个不同数组

问题描述 投票:0回答:2

我在我的角度应用程序中使用chartjs图表。而且我已经将标准的Web API结果用于图表。

this.httpClient.get(this.REST_API_SERVER).subscribe((data: any[])=>{
  console.log(data);

})  

数据是:

[
   { "label": "city-1", "data1": 200},
   { "label": "city-2", "data1": 450},
   { "label": "city-2", "data1": 950},
]

[
   { "label": "city-1", "data1": 200, "data2": 60 },
   { "label": "city-2", "data1": 450, "data2": 40 },
   { "label": "city-3", "data1": 950, "data2": 78 },
]

我的意思是,label是图表的标签,data1data2data3是图表的值。

所以我想将此响应数据拆分为两个不同的数组,如下所示。

var labels = [ "city-1", "city-3", "city-3"];
var data = [ 
              { "data": [ 200, 450, 950 ], "label": "data1" },
              { "data": [ 60,  40,  78 ], "label": "data2" }
           ];

在角度rxjs映射中可能吗?

angular chart.js angular7
2个回答
1
投票

您可以使用reduce()以所需的格式转换数据。

迭代给定数据,如果存在带有当前标签的项目,则将值附加到其data数组,如果不创建具有当前值的新数组项目。

let input = [
   { "label": "city-1", "data1": 200, "data2": 60 },
   { "label": "city-2", "data1": 450, "data2": 40 },
   { "label": "city-3", "data1": 950, "data2": 78 },
];

let result = input.reduce((acc, curr) => {
  acc.labels = acc.labels || [];
  acc.labels.push(curr.label);
  
  acc.data = acc.data || [];

  Object.entries(curr).forEach(([key, value]) => {
    if (key !== "label") {
      let item = acc.data.find(item => item.label === key);

      if (item) {
        item.data.push(value);
      } else {
        acc.data.push({
          "data": [value],
          "label": key
        });
      }
    }
  });

  return acc;
}, {});

let labels = result.labels;
let data = result.data;

console.log("Labels", labels);
console.log("Data", data);

0
投票

您可以在这里找到一个有效的脚本:

const list = [
   { "label": "city-1", "data1": 200, "data2": 60 },
   { "label": "city-2", "data1": 450, "data2": 40 },
   { "label": "city-3", "data1": 950, "data2": 78 },
]

const result = list.reduce((acc, item) => {
      const label = item['label'];
      acc[0].push(label);
      const keys = Object.keys(item).filter(key => key !== 'label');
      keys.forEach(key => {
        let labelItem = acc[1].find(value => value.label === key);
        if (!labelItem) {
          acc[1].push({ label:key, data: [item[key]] });
        } else {
          labelItem.data.push(item[key]);
        }
      });
      return acc;
    }, [[], []]);

console.log(result)

对于打字稿,您需要添加类型。

© www.soinside.com 2019 - 2024. All rights reserved.