[英]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.