Test Dynamically Fetching an Object Property

Benchmark created on


Setup

const obj = {
	"foo": {
		"bar": {
			"baz": {
				"oof": 1
			}
		}
	}
}

function v1(obj, path) {
  const pathParts = path.split('.');
  let currentObj = obj;

  for (const part of pathParts) {
    currentObj = currentObj?.[part];
    if (currentObj === undefined) {
      return undefined;
    }
  }

  return currentObj;
}

function v2(obj, path) {
  let currentObj = obj;
  let i = 0;

  while (i < path.length) {
    if (currentObj === null || typeof currentObj !== 'object') {
      return undefined;
    }

    let dotIndex = path.indexOf('.', i);
    if (dotIndex === -1) {
      dotIndex = path.length;
    }
    const part = path.substring(i, dotIndex);

    if (!(part in currentObj)) {
      return undefined;
    }

    currentObj = currentObj[part];
    i = dotIndex + 1;
  }

  return currentObj;
}

function v3(obj, path) {
  const pathParts = path.split('.');

  let currentObj = obj;
  for (const part of pathParts) {
    if (currentObj === null || typeof currentObj !== 'object' || !(part in currentObj)) {
      return undefined;
    }
    currentObj = currentObj[part];
  }

  return currentObj;
}

function v4(obj, path) {
  const pathParts = path.split('.');
  let currentObj = obj;
  let part;
  
  do {
  	currentObj = currentObj?.[part];
  } while (currentObj !== undefined && (part = partPaths.unshift()));
  return currentObj;
}

function v5(obj, path) {
  const pathParts = path.split('.');
  const length = pathParts.length;
  
  let currentObj = obj;
  let i;
  
  while (i < length && currentObj !== undefined) {
  	currentObj = currentObj?.[partPaths[i]];
  }
  return currentObj;
}

Test runner

Ready to run.

Testing in
TestOps/sec
v1 Found Property
v1(obj, "foo.bar.baz.oof")
ready
v2 Found Property
v2(obj, "foo.bar.baz.oof")
ready
v3 Found Property
v3(obj, "foo.bar.baz.oof")
ready
v4 Found Property
v4(obj, "foo.bar.baz.oof")
ready
v5 Found Property
v5(obj, "foo.bar.baz.oof")
ready

Revisions

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