最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert string to an attribute for a nested object in javascript - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Feb 21, 2013 at 12:52 Manu K Mohan asked Feb 21, 2013 at 12:20 Manu K MohanManu K Mohan 8334 gold badges9 silver badges29 bronze badges 10
  • A bination of two anti-patterns: with (obj) var result = eval(attr);. – dfsq Commented Feb 21, 2013 at 12:31
  • 1 possible duplicate of Accessing nested JavaScript objects with string key – Felix Kling Commented Feb 21, 2013 at 12:35
  • 1 Please read: 'There is no such thing as a "JSON object"'. What you have is a normal JavaScript object. – Felix Kling Commented Feb 21, 2013 at 12:36
  • @dfsq I dont get it. eval(attr) will give "Reference Error for key1" Can you please explain more clearly? – Manu K Mohan Commented Feb 21, 2013 at 12:37
  • @ManuKMohan eval(attr_string); – dfsq Commented Feb 21, 2013 at 12:41
 |  Show 5 more ments

4 Answers 4

Reset to default 3

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/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!.

Is this 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'

fixing up @John's answer into a re-usable function (which I will be using 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, 'a.b.c'));
var target = obj;
const parts = attr_string.split(".");
for (var part in parts)
  target = target[part[part]];
发布评论

评论列表(0)

  1. 暂无评论