【问题标题】:Javascript (VueJS) Object with Array带有数组的 Javascript (VueJS) 对象
【发布时间】:2017-06-28 03:13:10
【问题描述】:
   {
  "data": {
    "id": 3,
    "name": "random",
    "email": "randon@yahoo",
    "created_at": "2017-02-06 18:16:06",
    "updated_at": "2017-02-06 18:16:06",
    "roles": [
      {
        "id": 1,
        "name": "ADMIN",
        "access": {
          "role4": true,
          "role3": true,
          "role2": true,
          "role1": true
        },
        "created_at": "-0001-11-30 00:00:00",
        "updated_at": "-0001-11-30 00:00:00"
      }
    ]
  }
}

我正在尝试访问“访问”并接收结果真/假,但它不起作用

currentUser.roles[0].access['role1'];

错误:无法读取未定义的属性“0”

但是

console.log(currentUser.roles[0].access['role1']); // returns true

currentUser.roles // gives me all the roles

数据通过 Laravel Transformer 传递到前端。

注意:使用 VueJs,这是内部方法:

【问题讨论】:

  • 不是data.roles[0].access['role1']吗?
  • 不,它是未定义的
  • 我的意思是...... currentUser 来自哪里?我在你的对象中找不到它
  • this.currentUser = data 如果我使用 this.currUser.id 或 data.id 是一样的
  • 所以在你的情况下console.log(currentUser.roles[0].access['role1']); 工作但currentUser.roles[0].access['role1']; 没有?嗯...如果没有更多信息和背景,我无法更进一步。

标签: javascript arrays object vue.js


【解决方案1】:

由于我没有看到完整的代码,我可以假设。 首先你有匹配数据与

this.currentUser = data //data that you retrieve

然后访问它:

this.currentUser.roles[0].access['role1']

【讨论】:

    【解决方案2】:

    VueComponent 上下文中,data 属性传播到其this 上下文中。因此:

     this.roles[0].access['role1']
    

    【讨论】:

    • 但首先我需要参考当前登录的用户。这就是为什么 currentUser。
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2017-06-24
    • 2021-06-06
    • 2019-03-19
    • 2021-08-15
    • 1970-01-01
    • 2019-05-01
    • 2019-09-27
    相关资源
    最近更新 更多