Convert JavaScript string in dot notation into an object reference

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

    If you expect to dereference the same path many times, building a function for each dot notation path actually has the best performance by far (expanding on the perf tests James Wilkins linked to in comments above).

    var path = 'a.b.x';
    var getter = new Function("obj", "return obj." + path + ";");
    getter(obj);
    

    Using the Function constructor has some of the same drawbacks as eval() in terms of security and worst-case performance, but IMO it's a badly underused tool for cases where you need a combination of extreme dynamism and high performance. I use this methodology to build array filter functions and call them inside an AngularJS digest loop. My profiles consistently show the array.filter() step taking less than 1ms to dereference and filter about 2000 complex objects, using dynamically-defined paths 3-4 levels deep.

    A similar methodology could be used to create setter functions, of course:

    var setter = new Function("obj", "newval", "obj." + path + " = newval;");
    setter(obj, "some new val");
    

提交回复
热议问题