繁体   English   中英

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

[英]what is the correct way to destructure a nested json object with fetch?

我正在尝试为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)
      }
  }

谢谢你的帮助!

提取返回响应

要进入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)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM