arraysangulartypescriptchart.jsng2-charts

Angular Push JSON data into Array


im trying to figure out how to push a json object into an array using typescript. I managed to do it with one value of the json object but i need to do it with the second one too.

Heres the Structure of the JSON file:

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"
    }
  ];

And heres my code:

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];
    }
  }

It works so far if i only push one object value into the dataset array, but if i try it with += it doesnt work. What am i doing wrong?

I tried multiple stuff but nothing seems to work. I just can't wrap my head around it. Thanks in advance!


Solution

  • From your code, I believe that you try to achieve a bar chart with multiple datasets.

    You should have 2 different datasets:

    [ 
      { 
        "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

    Output

    enter image description here