Set value in JSON by a path using lodash or underscore

JavaScript performance comparison

Test case created

Preparation code

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/1.3.1/lodash.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    json = {a:[{b:'c'}]};
   
    function setValue1(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);
    }
   
    function setValue2(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];
        }
      }
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
With Reduce
setValue1('a.0.b', 'd', json);
pending…
With Loop
setValue2('a.0.b', 'd', json);
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment