Convert JavaScript string in dot notation into an object reference

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

    Many years since the original post. Now there is a great library called 'object-path'. https://github.com/mariocasciaro/object-path

    Available on NPM and BOWER https://www.npmjs.com/package/object-path

    It's as easy as:

    objectPath.get(obj, "a.c.1");  //returns "f"
    objectPath.set(obj, "a.j.0.f", "m");
    

    And works for deeply nested properties and arrays.

提交回复
热议问题