Setting a depth in an object literal by a string of dot notation?

后端 未结 4 1247
滥情空心
滥情空心 2020-12-10 09:37

There are plenty of solutions out there to check/access an object literal giving a string of dot notation, but what I need to do is SET an object literal based on a string o

相关标签:
4条回答
  • 2020-12-10 10:04

    My version:

    function setDepth(obj, path, value) {
        var tags = path.split("."), len = tags.length - 1;
        for (var i = 0; i < len; i++) {
            obj = obj[tags[i]];
        }
        obj[tags[len]] = value;
    }
    

    Working demo: http://jsfiddle.net/jfriend00/Sxz2z/

    0 讨论(0)
  • 2020-12-10 10:05

    This is one way of doing it:

    function setDepth(obj, path, value) {
        var levels = path.split(".");
        var curLevel = obj;
        var i = 0;
        while (i < levels.length-1) {
            curLevel = curLevel[levels[i]];
            i++;
        }
        curLevel[levels[levels.length-1]] = value;
    }
    

    Working demo.

    0 讨论(0)
  • 2020-12-10 10:11

    I modified Elliot's answer to let it add new nodes if they don't exist.

    var settings = {};
    
    function set(key, value) {
      /**
             * Dot notation loop: http://stackoverflow.com/a/10253459/607354
             */
      var levels = key.split(".");
      var curLevel = settings;
      var i = 0;
      while (i < levels.length-1) {
        if(typeof curLevel[levels[i]] === 'undefined') {
          curLevel[levels[i]] = {};
        }
    
        curLevel = curLevel[levels[i]];
        i++;
      }
      curLevel[levels[levels.length-1]] = value;
    
      return settings;
    }
    
    set('this.is.my.setting.key', true);
    set('this.is.my.setting.key2', 'hello');

    0 讨论(0)
  • 2020-12-10 10:11

    Just do it like this:

    new Function('_', 'val', '_.' + path + ' = val')(obj, value);
    

    In your case:

    var obj = { 
       'a': 1, 
       'b': 2, 
        'c': { 
          'nest': true 
        } 
    };
    
    new Function('_', 'val', '_.c.nest' + ' = val')(obj, false);
    
    0 讨论(0)
提交回复
热议问题