Last active
February 14, 2024 01:53
-
-
Save dotproto/999879c16dd5fac43d23dce900e25ff6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.