1

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
  • 19,662
  • 1
  • 29
  • 40
tiger_groove
  • 956
  • 2
  • 17
  • 46

2 Answers2

4

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
  • 53,704
  • 14
  • 91
  • 128
0
You can do like this something['bar'] 

Where bar is your variable that has been converted to string, in our case:

jsonObj[`${jsonKey}`]