简体   繁体   中英

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 . 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. Alternatively I've tried 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.

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.

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 .

This is how should be your code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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