3

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?

14
  • 2
    this -> jsonObj[jsonValue] Commented Mar 20, 2018 at 2:14
  • @btzr Even if this is my jsonValue? response.result.status.name Commented Mar 20, 2018 at 2:15
  • 4
    Possible duplicate of Dynamically access object property using variable Commented Mar 20, 2018 at 2:16
  • is that a string (status.name) ? Commented Mar 20, 2018 at 2:17
  • What is the result when you console log jsonObj? Commented Mar 20, 2018 at 2:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, i see now. This makes much more sense! Thank you !
this breaks in some cases (like objects being null). the question posted by @btzr constains an answer with a safer implementation: stackoverflow.com/a/45322101/347508
even object can be like {a : { "my-key": "my-value"}}
-1

You can use code like this:

something['bar'] 

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

jsonObj[`${jsonKey}`]

1 Comment

Why are you using string interpolation on the key, rather than just using the key variable directly as jsonObj[jsonKey]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.