简体   繁体   English

在JSON中访问嵌套对象的正确方法是什么?

[英]What is the correct way to access nested objects in JSON?

If I understand correctly, list in this code is an array that consists of objects . 如果我理解正确,那么此代码中的list是一个由objects组成的数组 I want to access temp in the main object and thought main.temp would do the trick, but I get an error message stating it's undefined. 我想访问主对象中的temp,并认为main.temp可以解决问题,但是我收到一条错误消息,指出它是未定义的。 Alternatively I've tried list[1].main.temp . 另外,我尝试过list[1].main.temp What is the correct way to access nested arrays like this? 像这样访问嵌套数组的正确方法是什么?

在此处输入图片说明

What is the correct way to access nested arrays like this? 像这样访问嵌套数组的正确方法是什么?

First of all these aren't nested arrays, but array of objects instead and in an array we access the items by index, and in objects we access them(entries) by keys. 首先,这些不是嵌套数组,而是对象数组,在array我们通过索引访问项目,而在objects我们通过键访问它们(条目)。

So in your case list[0] is an object where list[0].dt is an entry and list[0].main is another entry of the object , so dt isn't at index 0 like you mentioned in your comment. 因此,在您的情况下, list[0]是一个object ,其中list[0].dt是一个条目,而list[0].main是该object另一个条目,因此dt不在索引0就像您在注释中提到的那样。

And to access all your array main.temp properties you need to loop throught the array elements using one of the Array built-in methods or just a for loop , because using static indexes in list[1].main.temp will just get the temp property of the firts element in the array and may throw an exception if this index is higner than the array.length . 要访问所有数组main.temp属性,您需要使用Array内置方法之一或for loop array元素,因为在list[1].main.temp使用静态索引只会得到数组中firts元素的temp属性,如果此索引比array.length ,则可能引发异常。

This is how should be your code: 这应该是您的代码:

for(var i=0; i<list.length; i++){
    console.log(list[i].main.temp);
}

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

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