Convert string to an attribute for a nested object in javascript

javascript

Solution

Thanks @dfsq for remembering me the use of `eval`.

Here is what I was expecting, a simple way to evaluate the objects string attribute.

var obj = { key1 : {key2 : "value1", key3 : "value2"}};
var attr_string = "key1.key2";

var result = eval("obj."+attr_string);

There is no need of splitting the string with `"."` and then putting it in a loop to get the value. `eval` can evaluate any string with javascript code statement.

Be noted: although the code functions as expected, `eval` should not be used!!!

see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!.

Problem

I am trying to access a string `"key1.key2"` as properties of an object. For example : ``` var obj = { key1 : {key2 : "value1", key3 : "value2"}}; var attr_string = "key1.key2"; ``` The variable `attr_string` is a string of attributes in a nested object joined by `"."`. It can be of any depth like `"key1.key2.key3.key4..."` I want something like `obj.attr_string` to give the value of `obj["key1"]["key2"]` that is `"value1"` How to achieve this?

Original source

Related problems