Find object deep-nested value (v4)

Revision 4 of this benchmark created by gregp on


Setup

var obj = {foo: {bar: {baz: 123}}};
    
    function find_forloop(o, path) {
      var obj = o;
      var parts = path.split(".");
      for(var i=0;obj !== undefined && i<parts.length;i++) {
         obj = obj[parts[i]];
      }
      return obj;
    }
    
    function find_using_reduce(obj, path) {
      path.split('.').reduce(function (obj, key) {
        return obj[key] || {};
      }, obj);
    }
    
    var STOP = "stop";
    
    function find_using_reduce_die_fast(obj, path) {
      try {
        path.split('.').reduce(function (obj, key) {
          if (obj[key]) {
            return obj[key];
          }
    
          throw STOP;
        }, obj);
      } catch (err) {
        if (STOP === err) {
          return;
        }
    
        // rethrow
        throw err;
      }
    }
    
    function find_using_while(obj, path) {
      var parts = path.split('.');
    
      while (obj && parts.length) {
        obj = obj[parts.shift()];
      }
    
      return obj;
    }
    
    function find_InSteps(root, path) {
                        if (root && path) {
                            var steps = path.split('.'),
                                curStep = root,
                                stpI = 0, stpLen, step;
                            for (stpLen = steps.length; stpI < stpLen; stpI++)
                                /*for (stpI in steps)*/ {
                                step = steps[stpI];
                                if (curStep[step] !== undefined) {
                                    curStep = curStep[step];
                                }
                                else {
                                    return undefined;
                                }
                            }
                            return curStep;
                        }
                        return undefined;
                    }

Test runner

Ready to run.

Testing in
TestOps/sec
reduce
find_using_reduce(obj, "foo.bar.baz");
find_using_reduce(obj, "moo.bar.baz");
ready
reduce + throw
find_using_reduce_die_fast(obj, "foo.bar.baz");
find_using_reduce_die_fast(obj, "moo.bar.baz");
ready
while
find_using_while(obj, "foo.bar.baz");
find_using_while(obj, "moo.bar.baz");
ready
evalPath
find_InSteps(obj, "foo.bar.baz");
find_InSteps(obj, "moo.bar.baz");
ready
simple for loop
find_forloop(obj, "foo.bar.baz");
find_forloop(obj, "moo.bar.baz");
ready

Revisions

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

  • Revision 1: published by Aleksey V Zapparov on
  • Revision 3: published by Arthur Puszynski on
  • Revision 4: published by gregp on