简体   繁体   English

使用lodash或下划线通过路径在JSON中设置值

[英]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.0.b"的路径字符串在JSON中设置值,以获得如下所示的JSON:

{
  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'}]} 所以调用setValue('a.0.b', 'd', {a:[{b:'c'}]})会将json更改为{a:[{b:'d'}]}

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. 我对两种可能的解决方案进行了基准测试,看起来循环遍历对象和路径比使用reduce函数更快。 See the JSPerf tests here: http://jsperf.com/set-value-in-json-by-a-path-using-lodash-or-underscore 请参阅此处的JSPerf测试: 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];
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM