0

Assume I have the following object:

var jsonObj = {  
  "response":{  
    "result":{  
      "status":{
        "name": "Eric"
      }
    }
  }
}

And now i'd like to dynamically access a nested property:

jsonKey = "response.result.status.name";
console.log("the status is: " + jsonObj.jsonKey);  //I cannot call jsonObj.jsonKey here

Is there any way to achieve this?

kritzikratzi
  • 18,342
  • 1
  • 28
  • 39
tiger_groove
  • 866
  • 1
  • 15
  • 38

1 Answers1

3

You cannot access a deeply nested property as simple as you expect. Instead you need to use the obj[propertyNameAsString] syntax to dive deeper into the response one by one.

This would be one way of getting there:

let response = {
  "response": {
    "method": "GetStatus",
    "module": "Module",
    "data": null,
    "result": {
      "status": {
        "name": "Eric"
      },
      "id": 1
    },
    "result_code": {
      "error_code": 0
    }
  }
}

let keyString = "response.result.status.name"
let keyArray = keyString.split('.'); // [ "response", "result", "status", "name" ]
var result = response;

for (key of keyArray) {
  result = result[key]
}

console.log(result)

Please be aware that this is not failsafe against cases where one of those strings in keyArray does not exist as a property on the preceding object.

connexo
  • 49,059
  • 13
  • 74
  • 108