Convert JavaScript string in dot notation into an object reference

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

    var find = function(root, path) {
      var segments = path.split('.'),
          cursor = root,
          target;
    
      for (var i = 0; i < segments.length; ++i) {
       target = cursor[segments[i]];
       if (typeof target == "undefined") return void 0;
       cursor = target;
      }
    
      return cursor;
    };
    
    var obj = { a: { b: '1', c: '2' } }
    find(obj, "a.b"); // 1
    
    var set = function (root, path, value) {
       var segments = path.split('.'),
           cursor = root,
           target;
    
       for (var i = 0; i < segments.length - 1; ++i) {
          cursor = cursor[segments[i]] || { };
       }
    
       cursor[segments[segments.length - 1]] = value;
    };
    
    set(obj, "a.k", function () { console.log("hello world"); });
    
    find(obj, "a.k")(); // hello world
    

提交回复
热议问题