[Chartjs]-What is the correct way to destructure a nested json object with fetch?

5👍

fetch returns a response

to get to the json, you need to await response.json()

like so

async mounted() {
  this.loaded = false
  try {
    const response = await fetch("http://localhost:8000/api/report/" + this.$route.params.id)
    const {report: {usage: {license}}} = await response.json();
    this.chartData = license
    this.loaded = true
  } catch (e) {
    console.error(e)
  }
}

Here’s my last answer combined with this answer in a working snippet

class Player {
    constructor(player_id, score) {
        this.player_id = player_id;
        this.scores = [score];
        this.total = score;
    }

    addScore(score) {
        this.total += score;
        this.scores.push(score);
        return score;
    }

    get average() {
        return this.scores.length ? this.total / this.scores.length : 0;
    }

    resetScore() {
        this.scores = [];
        this.score = 0;
    }

};
class LeaderBoard {
    constructor() {
        this.players = {};
    }
    addScore(player_id, score) {
        if (!this.players[player_id]) {
            this.players[player_id] = new Player(player_id, score);
        } else {
            this.players[player_id].addScore(score);
        }
        return this.players[player_id].average.toFixed(1);
    }
    top = (num_players) => {
      return Object.values(this.players).sort((a, b) => (a.average - b.average)).slice(0, num_players);
    }

};
let x = new LeaderBoard();
x.addScore(1, 4);
x.addScore(2, 3);
x.addScore(3, 2);
x.addScore(4, 1);
console.log(x.top(3));

Leave a comment