Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value in JSON by a path using lodash or underscore

I wanna set the value in a JSON using a path string like this "a.0.b" for a JSON that looks like this:

{
  a: [
    {
      b: 'c'
    }
  ]
}

I came up with this solution but I wonder if there is a simpler way to write this:

function setValue(path, value, json) {
  var keys = path.split('.');
  _.reduce(keys, function(obj, key, i) {
    if (i === keys.length - 1) {
      obj[key] = value;
    } else {
      return obj[key];
    }
  }, json);
}

so calling setValue('a.0.b', 'd', {a:[{b:'c'}]}) would change the json to {a:[{b:'d'}]}

like image 421
Andreas Köberle Avatar asked Apr 08 '13 09:04

Andreas Köberle


1 Answers

Here's a solution. I benchmarked the two possible solutions and it seems looping over object and path is faster than using the reduce function. See the JSPerf tests here: http://jsperf.com/set-value-in-json-by-a-path-using-lodash-or-underscore

function setValue(path, val, obj) {
  var fields = path.split('.');
  var result = obj;
  for (var i = 0, n = fields.length; i < n && result !== undefined; i++) {
    var field = fields[i];
    if (i === n - 1) {
      result[field] = val;
    } else {
      if (typeof result[field] === 'undefined' || !_.isObject(result[field])) {
        result[field] = {};
      }
      result = result[field];
    }
  }
}
like image 75
Rocky Avatar answered Oct 04 '22 03:10

Rocky