Chartjs-How to take data from an API and create a chart on that using Chart.js and Angular 8?

0👍

You could use Array.prototype.map():

public barChartLabels = this.weather.list.map(item => item.main);

public barChartData = [
    {
        data: this.weather.list.map(item => item.main.temp),
        label: 'Temperature',
    },
    {
        data: this.weather.list.map(item => item.main.pressure),
        label: 'Pressure',
    },
    {
        data: this.weather.list.map(item => item.main.sea_level),
        label: 'Sea Level'
    },
];

If you are only using the list property of the data, you could change this assignment:

this.weather = data

To:

this.weather = data.list

And shorten the map() calls to:

public barChartLabels = this.weather.map(item => item.main);

public barChartData = [
    {
        data: this.weather.map(item => item.main.temp),
        label: 'Temperature',
    },
    {
        data: this.weather.map(item => item.main.pressure),
        label: 'Pressure',
    },
    {
        data: this.weather.map(item => item.main.sea_level),
        label: 'Sea Level'
    },
];

Leave a comment