DEV Community

Jen Chan
Jen Chan

Posted on

Dumb Breakthrough moment: JSON Object Array Access

After being stuck on this for half an hour a friend takes a look at my Vue and server code.

"You're not actually accessing the arrays, you're only receiving the response as an object."

Seinfeld music plays

This is what I saw when I console.log-ed this.response.data

JSON response object from call to a Google Sheets endpoint. This object included an array of row objects, which contained arrays of info about cats that I couldn't access and thus iterate through in a v-for loop

This is what I should see if I want to iterate through arrays of row objects: this.response.data.rows

JSON response object targetting its arrays of row-objects by dot-notation

Thanks to Conan Lai for clearing that up.

Top comments (7)

Collapse
 
leanminmachine profile image
leanminmachine

Well i would imagine the data object to contain the rows. in the json response it says Object, followed by rows: Array (27). Which means .rows contains an array containing 27 elements. :P

Collapse
 
binarypatrick profile image
BinaryPatrick

I can't tell you how often people are tripped up on json response types. Assuming an array and getting a root object. Helping with troubleshooting, I'm always asking, what type of bracket is it, curly or square.

Collapse
 
ben profile image
Ben Halpern

Speaking of trip ups: NodeList.

Looks and smells like an Array but don’t try calling forEach!

Thread Thread
 
leanminmachine profile image
leanminmachine • Edited

Huh. MDN docs @ developer.mozilla.org/en-US/docs/W... says this:

Although NodeList is not an Array, it is possible to iterate over it with forEach(). It can also be converted to a real Array using Array.from().

However, some older browsers have not implemented NodeList.forEach() nor Array.from(). This can be circumvented by using Array.prototype.forEach() — see this document's Example.

I'm not too familiar with NodeList though.

Thread Thread
 
ben profile image
Ben Halpern

It’s not that dealing with this one way or another is that much of a pain, it’s just frustrating that it often trips people up when they’re expecting array behavior and don’t know what to do when it’s almost array behavior.

Thread Thread
 
lvl99 profile image
Matt Scheurich

Things like Set and Map do well to hint that they are not arrays by using the size property instead of length. Should NodeList perhaps implement this prop name hint, or is it just a matter of browser support?

Thread Thread
 
nektro profile image
Meghan (she/her)

NodeList should inherit Array though. Set and Map are entirely different data structures.