Convert string to attribute for nested object in javascript

I am trying to access the string "key1.key2" as object properties. For instance:

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

The attr_string variable is an attribute string in a nested object connected to "." . It can be of any depth, like "key1.key2.key3.key4..."

I need something like obj.attr_string to assign the value obj["key1"]["key2"] "value1"

How to do it?

+4
source share
4 answers

Thanks @dfsq for recalling the use of eval .

Here is what I expected, an easy way to evaluate the attribute of an object string.

 var obj = { key1 : {key2 : "value1", key3 : "value2"}}; var attr_string = "key1.key2"; var result = eval("obj."+attr_string); 

There is no need to split the string into "." and then put it in a loop to get the value. eval can evaluate any string using javascript code instructions.

+1
source
 var target = obj; for (var part in attr_string.split(".")) target = target[part]; 
0
source

Is that what you are after?

 var obj = { key1: { key2A: 'x', key2B: { key3: 'y' } } }, attr_string = 'key1.key2B.key3', find = function ( obj, str ) { var index = 0, arr = str.split( '.' ); if ( arr.length ) { while ( typeof obj === 'object' && arr[ index ] in obj ) { obj = obj[ arr[ index ] ]; index++; } } return obj; }; find( obj, attr_string ); // Returns 'y' 
0
source

fixing @John's answer to a reusable function (which I will use myself)

 function nested(obj, attrString){ var path = attrString.split("."); for (var i in path){ obj = obj[path[i]]; } return obj; } // test it out... x = {a:{b:{c:"happy days"}}}; console.log(nested(x, 'a')); console.log(nested(x, 'a.b')); console.log(nested(x, 'abc')); 
0
source

All Articles