Javascript数组值未定义?

时间:2017-03-16 03:36:08

标签: javascript arrays json

我目前正在开发一个REST API /网站项目,我的REST API必须通过响应从服务器返回一个对象数组,并使用GSON从数据中生成一个Json数组。但是,当试图从网站的javascript数组中获取值时,我一直未定义。这是数组:

var userArr =[
  {
    "0x1": {
      "firstName": "Test1",
      "lastName": "Test1",
      "hobbies": [
        {
          "id": 1,
          "name": "Fodbold",
          "people": [
            "0x1"
          ]
        }
      ],
      "id": 1,
      "address": {
        "id": 1,
        "street": "Street1",
        "cityInfo": {
          "id": 1,
          "zipCode": "0555",
          "city": "Scanning"
        },
        "infoList": [
          "0x1",
          "0x2"
        ]
      },
      "phones": [
        {
          "id": 1,
          "number": "123124",
          "info": "0x1"
        }
      ]
    }
];

当我尝试调用userArr [0] .firstName时,即使数据存在,我也会收到错误消息,说明它未定义。这是来自一个get调用,我在我的REST API中用我的REST API进行调用,它返回这个特定的数组。我已经尝试在数组中循环,内部有多个对象,但我根本无法检索任何信息。

4 个答案:

答案 0 :(得分:2)

您的userArr是一个没有firstName属性的对象数组。由于某种原因,他们只有一个名为0x1的属性。此0x1属性具有firstName属性。

您可以使用以下表示法访问firstName 0x1属性:

userArr[0]["0x1"].firstName

以下是工作演示:



var userArr = [{
  "0x1": {
    "firstName": "Test1",
    "lastName": "Test1",
    "hobbies": [{
      "id": 1,
      "name": "Fodbold",
      "people": [
        "0x1"
      ]
    }],
    "id": 1,
    "address": {
      "id": 1,
      "street": "Street1",
      "cityInfo": {
        "id": 1,
        "zipCode": "0555",
        "city": "Scanning"
      },
      "infoList": [
        "0x1",
        "0x2"
      ]
    },
    "phones": [{
      "id": 1,
      "number": "123124",
      "info": "0x1"
    }]
  }
}];

console.log(userArr[0]["0x1"].firstName);




顺便说一句,代码中数组末尾有一个缺少的结束}括号。

答案 1 :(得分:1)

我认为如果以这种方式编写此代码,则很容易理解并找到问题

var userArr =[
  {
    "0x1": {
      "firstName": "Test1",
      "lastName": "Test1",
      "hobbies": [{"id": 1,"name": "Fodbold","people": ["0x1"]}],
      "id": 1,
      "address": {"id": 1,"street": "Street1","cityInfo": {"id": 1,"zipCode": "0555","city": "Scanning"},
      "infoList": ["0x1","0x2"]},
      "phones": [{"id": 1,"number": "123124","info": "0x1"}]
    }
  }
];

您还错过了最后一个第二个括号。 然后你可以使用这个console.log(userArr[0]["0x1"].firstName);

答案 2 :(得分:0)

尝试这个

userArr[0]["0x1"].firstName

答案 3 :(得分:0)

包含值"0x1"是动态的,您可以使用Object.keys(userArr[0])[0]来获取对象的第一个键。

这是解决方案:

var userArr = [{
  "0x1": {
    "firstName": "Test1",
    "lastName": "Test1",
    "hobbies": [{
      "id": 1,
      "name": "Fodbold",
      "people": [
        "0x1"
      ]
    }],
    "id": 1,
    "address": {
      "id": 1,
      "street": "Street1",
      "cityInfo": {
        "id": 1,
        "zipCode": "0555",
        "city": "Scanning"
      },
      "infoList": [
        "0x1",
        "0x2"
      ]
    },
    "phones": [{
      "id": 1,
      "number": "123124",
      "info": "0x1"
    }]
  }
}];

console.log(userArr[0][Object.keys(userArr[0])[0]].firstName);