Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active February 14, 2024 01:53
Show Gist options
  • Save dotproto/999879c16dd5fac43d23dce900e25ff6 to your computer and use it in GitHub Desktop.
Save dotproto/999879c16dd5fac43d23dce900e25ff6 to your computer and use it in GitHub Desktop.
let sourceObject = { foo: { bar: { baz: { qux: { value: "Hit!" } } } } };
sourceObject.foo[Symbol.for('symbol')] = 'symbol value';
function lookup(object, path) {
path = Array.isArray(path) ? path : path.split('.');
for(let i = 0; i < path.length; i++) {
object = object[path[i]];
if (!object) break;
}
return object;
}
console.log('good arr:', lookup(sourceObject, ['foo', Symbol.for('symbol')]));
console.log('good str:', lookup(sourceObject, "foo.bar.baz.qux") );
console.log('bad str:', lookup(sourceObject, "foo.bar.baz.FAIL") );
console.log('bad str:', lookup(sourceObject, "foo.bar.FAIL.qux") );
console.log('bad str:', lookup(sourceObject, "FAIL.bar.baz.qux") );
@dotproto
Copy link
Author

Mmmm. Rev 1 of this version uses recursion, but I'm not sure I want to incur the cost of additional function calls. Ideally I'd like to be able to use this method in critical path logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment