Search code examples
angularforeachng2-google-chart

Format object from API call to dataTable format on Google Charts (ng2-google-charts)


I'm using ng2-google-charts to build a geoChart in an Angular 10 project. Everything works good with fixed data, the problem I have is that I'm not sure how to format (and add) the data from an API call.

This is my geoChart property that works perfectly with fixed data

public geoChart: GoogleChartInterface = {
   chartType: 'GeoChart',    
   dataTable: [
     ['Country', 'Ice Machines'],
     ['Austria', 1],
     ['Belgium', 2],
     ['Bulgaria', 3],    
   ],
   options: {},
};

This is the object (data.response) that I receive from the API --> [{…}, {…}, {…}, {…}, {…}, {…}]

0: {paisCode: "DE", total: 1}
1: {paisCode: "DK", total: 1}
2: {paisCode: "ES", total: 1}
3: {paisCode: "FR", total: 1}
4: {paisCode: "NL", total: 1}
5: {paisCode: "RO", total: 1}
length: 6

This is what I'm trying:

data.response.forEach(element => {
   let countryCode = element.paisCode;
   let totalPerCountry = element.total;
   //formattedDataMap +=  "[" + "'" + countryCode +"'" + ',' + totalPerCountry + "],";
   this.geoChart.dataTable.push('[' + countryCode + ',' + totalPerCountry + ']')
   formattedDataMap.push('[' + countryCode + ',' + totalPerCountry + ']')
   //console.log(formattedDataMap);
})

But the data is not added correctly:

0: (2) ["Country", "Total"]
1: (2) ["Austria", 1]
2: (2) ["Belgium", 2]
3: (2) ["Bulgaria", 3]
4: "[DE,1]"
5: "[DK,1]"
6: "[ES,3]"
7: "[FR,1]"
8: "[NL,1]"
9: "[RO,1]"

Update: I've updated my method, however nothing happens to the array. It's the same size and has the same elements.

  async myMethod() {
     if (this.account.email) {
        (await this.myService.MyMethod())
        .pipe(first())
        .subscribe(async (data: any) => {        
           this.geoChart.dataTable.concat(                
             data.response.reduce((acc, curr) => {
             acc.push([curr['paisCode'], curr['total']]);
             return acc;
           }, [])
        ); 
        console.log(this.geoChart.dataTable);
    });       
   }
 }

Solution

  • Using map worked:

       data.response.map(item => {
          this.geoChart.dataTable.push([item.paisCode, item.total]);
       })