cucuru cucuru - 1 month ago 13
jQuery Question

Get child nodes from an object

I have an object with some dynamic keys. I'm able to read the key name, but not the value:

var response = {
"keyOne": {
"keyChanged": {
"keyTwo": {
"keyINeed": "myData"
}
}
}
}

var myKey = Object.keys(response.keyOne)[0];
var myValue = response.keyOne."something".keyTwo.keyINeed


How can I do it?

Answer

To achieve this you need to use bracket notation, as you're providing the key of the object in a variable. Try this:

var response = {
  "keyOne": {
    "keyChanged": {
      "keyTwo": {
        "keyINeed": "myData"
      }
    }
  }
}


var myKey = Object.keys(response.keyOne)[0];
var myValue = response.keyOne[myKey].keyTwo.keyINeed; // note the [] here

console.log(myKey)
console.log(myValue);