With a single property this is fairly easy:
var jsonobj = {
"test": "ok"
}
var propname = "test";
// Will alert "ok"
alert(jsonobj[propname]);
But what I want to do is use a nested property:
var jsonobj = {
"test": {
"test2": "ok"
}
}
var propname = "test.test2";
// Alerts undefined
alert(jsonobj[propname]);
Is there any way of selecting a nested “dynamic” property?
I know I can do jsonobj.test.test2, but the problem is that propname can change to a property that goes 1,2 or 3 levels deep. (e.g test, test.test2, …)
E.g.
The benefit in using this is that it won’t throw an error if you try accessing something that doesn’t exist — it’ll gracefully return
undefined.EDIT:
In the comment, Andy mentioned that this doesn’t throw errors where one might expect it to. I agree that getting
undefinedis a little bit generic and there is no way to tell whether your value was really resolved. So, to remedy that, try this:It’ll return an UNRESOLVED object that can be checked like so:
It’s not perfect, but it is (IMO) the best way to determine an unresolved namespace without having to throw errors. If you want errors, then just go ahead with: