Question

If I have a Javascript object, parsed from JSON, that’s nested three deep, and I don’t know the key for the middle one, how to I access it and its contents?

The actual data I’m working with is from the Github API. For this example, I want the file names for all my gists.

[
  {
    "url": "https://api.github.com/gists/11164200",
    "forks_url": "https://api.github.com/gists/11164200/forks",
    "commits_url": "https://api.github.com/gists/11164200/commits",
    "id": "11164200",
    "git_pull_url": "https://gist.github.com/11164200.git",
    "git_push_url": "https://gist.github.com/11164200.git",
    "html_url": "https://gist.github.com/11164200",
    "files": {
      "testing.md": {
        "filename": "testing.md",
        "type": "text/plain",
        "language": "Markdown",
        "raw_url": "https://gist.githubusercontent.com/omphalosskeptic/11164200/raw/3582779a4925ea514382cedb7d077d00c231f3eb/testing.md",
        "size": 4254
      }
    }, // [ ... continues]

My Javascript skills are rudimentary. Normally I can find what I’m looking for with enough research but not this time. Originally I expected it would be something like: responseObj[0].files[0].filename.

If possible I’d like to keep this plain Javascript.

Thanks!

Was it helpful?

Solution

Based on the sample you posted, the files property is not an array, so can't be accessed by an indexer. This is a case where you would use a for-in loop rather than a regular for loop.

for(var p in responseObj[0].files) {                 
  if ( responseObj[0].files.hasOwnProperty (p) ) {   
    p; // p is your unknown property name
    responseObj[0].files[p]; // is the object which you can use to access 
                             // its own properties (filename, type, etc)           
  }                                                                                                           
}

The hasOwnProperty check will skip the automatic members like toString and only return those manually defined on the object.

OTHER TIPS

If you want to iterate over them, do something like

for (var fileID in responseObj[0].files) {
    var file = responseObj[0].files[fileID];
    var filename = file.filename;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top