开发者

Accessing nested Javascript JSON properties through Variables

Say I have a config file in which I have paths to JSON properties. My JSON looks like:

开发者_开发知识库
var test = { test: { test2: { test3: 1 } } }

and I have a string str = "test.test2.test3"

I know I can access the top level one like this: var foo = "test", test[foo]

But test["test.test2.test3"] does not work. On the other hand test["test"]["test2"]["test3"] works, but this is not a one liner if I have more complex objects (some can be 5 levels in, some can be 3 etc)

Is there any way to access this property directly instead of splitting on the dot and looping through?


with(test) eval(str);

Did anyone's head explode?

It's either that or

eval('test.' + str);

Take your pick from the bad practice basket.

Though for the first example if you actually want the value you'd want to do this

var value;
with(test) value = eval(str);

But that kind of takes away from the purity of this bad practice masterpiece.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜