使用fetch构造嵌套json对象的正确方法是什么?

问题描述 投票:5回答:1

我正在尝试为chart.js提取数字的许可证数组

API报告数据的形状为:

{
    "report": {
        "usage": {
            "chartLabels": [
                "'1-Mar', '2-Mar', '3-Mar', '4-Mar', '5-Mar', '6-Mar', '7-Mar', '8-Mar', '9-Mar',             '10-Mar', '11-Mar', '12-Mar', '13-Mar', '14-Mar', '15-Mar', '16-Mar', '17-Mar', '18-Mar',  '19-Mar', '20-Mar', '21-Mar', '22-Mar', '23-Mar', '24-Mar', '25-Mar', '26-Mar', '27-Mar', '28-Mar', '29-Mar', '30-Mar', '31-Mar'"
            ],
            "license": [
                "'3', '50', '56', '53', '60', '56', '47', '3', '39', '67', '60', '57', '61', '61', '8', '47', '49', '51', '49', '45', '42', '3', '3', '4', '4', '3', '3', '3', '3', '3', '4'"
            ],
       } 
   }
}

是否有可能用fetch进行destructure?我没有得到任何回到console.log(许可证)

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

谢谢你的帮助!

javascript chart.js destructuring
1个回答
5
投票

fetch返回响应

要到达json,你需要等待response.json()

像这样

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)
  }
}

这是我的最后一个答案,在一个工作片段中结合了这个答案

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));
© www.soinside.com 2019 - 2024. All rights reserved.