Convert JavaScript string in dot notation into an object reference

前端 未结 27 3019
梦如初夏
梦如初夏 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:32

    I have extended the elegant answer by ninjagecko so that the function handles both dotted and/or array style references, and so that an empty string causes the parent object to be returned.

    Here you go:

    string_to_ref = function (object, reference) {
        function arr_deref(o, ref, i) { return !ref ? o : (o[ref.slice(0, i ? -1 : ref.length)]) }
        function dot_deref(o, ref) { return ref.split('[').reduce(arr_deref, o); }
        return !reference ? object : reference.split('.').reduce(dot_deref, object);
    };
    

    See my working jsFiddle example here: http://jsfiddle.net/sc0ttyd/q7zyd/

提交回复
热议问题