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

时间:2019-04-10 03:02:41

标签: javascript chart.js destructuring

我正在尝试为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进行破坏?我没有用console.log(license)找回任何东西

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

获取返回响应

要访问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));