Dynamic deep setting for a JavaScript object

Viewed 29809

Given a string for a object property path, how do I set this property dynamically.

Given this sample object:

var obj = {
    a: {
        b: [ { c: 'Before' } ]
    }
};

It should be able to set the value with a helper function like this:

setToValue(obj, 'After', 'a.b.0.c');

I tried it with the following code. But parent is a copy if the variable not a reference.

function setToValue(obj, value, path) {
    var arrPath = path.split('.'),
        parent = obj;

    for (var i = 0, max = arrPath.length; i < max; i++) {
        parent = parent[arrPath[i]];
    }

    parent = value;
}
3 Answers

Here is a full solution.

Also creates objects if they don't exist.

function setValue(obj, path, value) {
  var a = path.split('.')
  var o = obj
  while (a.length - 1) {
    var n = a.shift()
    if (!(n in o)) o[n] = {}
    o = o[n]
  }
  o[a[0]] = value
}

function getValue(obj, path) {
  path = path.replace(/\[(\w+)\]/g, '.$1')
  path = path.replace(/^\./, '')
  var a = path.split('.')
  var o = obj
  while (a.length) {
    var n = a.shift()
    if (!(n in o)) return
    o = o[n]
  }
  return o
}
Related