Setting depth in object literal using dot notation string?

There are many solutions for checking / accessing an object literal providing a dot notation string, but I need to make a SET object literal based on a dot notation string. It is very important why I need to do this, and if this is not possible, I will come up with a different solution.

Here is what I would like to do:

var obj = { 
   'a': 1, 
   'b': 2, 
    'c': { 
      'nest': true 
    } 
};

I need a function that will work something like this:

setDepth(obj, 'c.nest', false);

This will change obj to this:

var obj = { 
   'a': 1, 
   'b': 2, 
    'c': { 
      'nest': false
    } 
};

I tried an hour and still could not find a good solution. Another help would be greatly appreciated!

+3
source share
4 answers

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/

+6
source

This is one way to do this:

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;
}

.

+2

I modified Elliot's answer to add new nodes if they do not 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');
Run codeHide result
+2
source

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
source

All Articles