【问题标题】:getting data from an object's array with vue.js使用 vue.js 从对象数组中获取数据
【发布时间】:2017-11-12 17:02:00
【问题描述】:

我正在尝试在 Vue.js 中访问以下数据

{"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}

self.player = response.name 有效。现在我需要self.point

methods: {
    fetchData: function() {
      var self = this;
      $.get("api/v1/players/1", function(response) {
        console.log(response);
        self.player = response.name;
        self.point = response.stats.points 
      });
    }
  }

到目前为止,我已经尝试过response.stats["points"]response.stats[2]response.stats[ { points } ]response.stats[points]

【问题讨论】:

    标签: arrays json vue.js


    【解决方案1】:

    您的 json 中的 stats 属性包含一个数组,其中第一个对象有一个名为 points 的属性

    所以使用response.stats[0].points


    请记住,stats 可能是一个数组是有原因的。将来它可能包含多个对象,因此始终使用第一个元素 [0] 可能不是一种有效的方法

    【讨论】:

      【解决方案2】:

      我觉得可以帮到你

      var json = JSON.parse(data);
      json.stats[0].points
      

      【讨论】:

        【解决方案3】:
        response = {"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
        

        如果你想访问名字

        console.log(response.name) // Westbrook
        

        如果要访问包含列表的统计数据,只需定位

        let stats=response.stats[0] //By getting the first index in the list
        

        在统计中获得积分

        console.log(stats.points) // 2588
        

        【讨论】:

          猜你喜欢
          • 2018-09-19
          • 2021-03-11
          • 2017-01-17
          • 2018-01-24
          • 2017-10-06
          • 1970-01-01
          • 2021-09-14
          • 2014-05-04
          • 2016-01-13
          相关资源
          最近更新 更多