[removed] How do I access values in nested objects if I don’t know the object’s key?

前端 未结 2 516
梦毁少年i
梦毁少年i 2021-01-28 03:37

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 d

相关标签:
2条回答
  • 2021-01-28 04:15

    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;
    }
    
    0 讨论(0)
  • 2021-01-28 04:27

    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.

    0 讨论(0)
提交回复
热议问题