ChartJS 将JSON数据Angular 推送到数组中

zzwlnbp8  于 2023-03-02  发布在  Chart.js
关注(0)|答案(2)|浏览(154)

我正在尝试弄清楚如何使用typescript将一个json对象推到一个数组中。我设法用json对象的一个值做了这件事,但我也需要用第二个值做这件事。
下面是JSON文件的结构:

data = [
    {
      "value1": 8,
      "value2": 9,
      "weekday": "2023-02-27"
    },
    {
      "value1": 8,
      "value2": 9,
      "weekday": "2023-02-28"
    },
    {
      "value1": 8,
      "value2": 9,
      "weekday": "2023-03-01"
    },
    {
      "value1": 8,
      "value2": 5,
      "weekday": "2023-03-02"
    },
    {
      "value1": 8,
      "value2": 9,
      "weekday": "2023-03-03"
    }
  ];

下面是我的代码:

setData() {
    let data_value1:any[] = [];
    let data_value2:any[] = [];
    let labels:any[] = [];
    this.data.forEach((entry) => {
      data_value1.push(entry['value1']);
      data_value2.push(entry['value2']);
      labels.push(getDayofWeek(entry['weekday']));
    });

    this.barChartData.labels = labels;
    
    let dataSet:any = {};
    dataSet['data'] += data_value1;
    dataSet['data'] += data_value2;
    dataSet['label'] = 'Test';
    this.barChartData.datasets.push(dataSet);

    function getDayofWeek(date:any) {
      const dayOfWeek = new Date(date).getDay();
      return isNaN(dayOfWeek) ? null : 
      ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][dayOfWeek];
    }
  }

到目前为止,如果我只将一个对象值推入数据集数组,它是有效的,但如果我尝试使用+=,它就不起作用了。
我尝试了很多方法,但是似乎都不起作用。我就是不能理解它。提前感谢!

xmq68pz9

xmq68pz91#

从您的代码中,我相信您尝试实现了一个具有多个数据集的条形图。
您应该有2个不同的数据集:

[ 
  { 
    "data": [ 8, 8, 8, 8, 8 ], 
    "label": "Label 1" 
  }, 
  { 
    "data": [ 9, 9, 9, 5, 9 ], 
    "label": "Label 2" 
  } 
]
let dataSet1: any = {
  data: data_value1,
  label: 'Label 1',
};

let dataSet2: any = {
  data: data_value2,
  label: 'Label 2',
};

this.barChartData.datasets.push(dataSet1);
this.barChartData.datasets.push(dataSet2);

Demo @ StackBlitz
产出

dbf7pr2w

dbf7pr2w2#

您正在尝试为chart.js条形图创建数据,该条形图具有与对象数组中的value1value2键的值对应的两个数据集。
下面是如何做到这一点:

const data = [{
    "value1": 8,
    "value2": 9,
    "weekday": "2023-02-27"
  }, {
    "value1": 8,
    "value2": 9,
    "weekday": "2023-02-28"
  }, {
    "value1": 8,
    "value2": 9,
    "weekday": "2023-03-01"
  }, {
    "value1": 8,
    "value2": 5,
    "weekday": "2023-03-02"
  }, {
    "value1": 8,
    "value2": 9,
    "weekday": "2023-03-03"
  }
];
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
                  'Friday', 'Saturday'];

function getDayofWeek(date: any) {
  const dayOfWeek = new Date(date).getDay();
  return isNaN(dayOfWeek) ? null : weekdays[dayOfWeek];
}

const config = {
  type: 'bar',
  labels: data.map(({weekday}) => getDayofWeek(weekday)),
  datasets: ['value1', 'value2'].map((k) => ({
    data: data.map((v) => v[k as keyof typeof data[number]])
  }))
};

console.log(config);

Playground链接

相关问题