Convert JavaScript string in dot notation into an object reference

前端 未结 27 3035
梦如初夏
梦如初夏 2020-11-21 05:09

Given a JS object

var obj = { a: { b: \'1\', c: \'2\' } }

and a string

\"a.b\"

how can I convert the stri

27条回答
  •  礼貌的吻别
    2020-11-21 05:58

    You can obtain value of an object member by dot notation with a single line of code:

    new Function('_', 'return _.' + path)(obj);
    

    In you case:

    var obj = { a: { b: '1', c: '2' } }
    var val = new Function('_', 'return _.a.b')(obj);
    

    To make it simple you may write a function like this:

    function objGet(obj, path){
        return new Function('_', 'return _.' + path)(obj);
    }
    

    Explanation:

    The Function constructor creates a new Function object. In JavaScript every function is actually a Function object. Syntax to create a function explicitly with Function constructor is:

    new Function ([arg1[, arg2[, ...argN]],] functionBody)
    

    where arguments(arg1 to argN) must be a string that corresponds to a valid javaScript identifier and functionBody is a string containing the javaScript statements comprising the function definition.

    In our case we take the advantage of string function body to retrieve object member with dot notation.

    Hope it helps.

提交回复
热议问题