我可以't访问JSON中的第一个对象

I can't access the first object in JSON

本文关键字:一个对象 JSON 访问 我可以      更新时间:2024-06-02

我尝试过遵循其他指南,但似乎都不起作用。我想在一个单独的JSON文件中获得第一个对象,它看起来像这样(片段):

{
    "employees": [{
        "occupation": "cook",
        "id": [{
            "address": {
                "postal_code": 12342,
                "city": "detroit"
              },
              "children": "none"
        ],
}
}
            // and so forth, there are more objects in the employees-array

我的代码片段如下:

$.getJSON(url, function(data) {
    $.each(data.employees, function(i, emp) {
        if (this.id.length) {
            console.log(this[0].address.city);
        }
    }

我想访问第一个对象的"地址"。如果我键入`console.log(this.address[0].city);,我将从"employees"中的每个对象中获得所有第一个"city"值。

事先谢谢!

each()内部,this将引用employee对象,因此需要将console.log()修改为:

$.each(data.employees, function(i, emp) {
    if (this.id.length) {
        console.log(this.id[0].address.city);
    }
});

为什么不在每个块中使用emp变量?

$.each(data.employees, function(i, emp) {
    if (emp.id.length) {
        console.log(emp.id[0].address.city);
    }
}

如果我正确理解了你的问题,并且根据@Velimir Tchatchevsky的评论,我认为你想要的是:

data.employees[0].id[0].address.city

jsfidle

最初您的对象是

{
    "employees": [{
        "occupation": "cook",
        "id": [{
            "address": {
                "postal_code": 12342,
                "city": "detroit"
              },
              "children": "none"
        ],
}
}

试试这个代码。

  $.each(data.employees, function(i, emp) { //each function will able access each employees
    if (this.id.length) {
        console.log(this.id[0].address.city); // at each employee get the first element of array id.
    }
}
  1. .each函数将遍历employees数组
  2. this.id[0]这将能够访问被标识为id的数组的第一个元素。在id内有一个地址对象。

               "address": {
                    "postal_code": 12342,
                    "city": "detroit"
                  }
    
  3. this.id[0].address:-此代码将为您提供地址对象。

                 {
                    "postal_code": 12342,
                    "city": "detroit"
                  }
    
  4. this.id[0].address.city:-在地址对象中,您将使用这段代码获得城市。给你答案。。

    "city": "detroit"
    

谢谢。

相关文章: