Skip to content

Instantly share code, notes, and snippets.

@vhoyer
Created January 5, 2022 17:53
Show Gist options
  • Save vhoyer/f5e1d653393ac7c15ae7f50d00b07272 to your computer and use it in GitHub Desktop.
Save vhoyer/f5e1d653393ac7c15ae7f50d00b07272 to your computer and use it in GitHub Desktop.
Proxy Handler for accessing deep properties arbitrarily, like `obj.a.b.c.d.e` without getting the `cannot access a of undefined`

DeepObjectNoopProxy.js

This is by no means a fail safe solution, use with care, and add to the exceptions object anything that you can't avoid.

const exceptions = {
// map: () => {},
};
const handler = {
get(target, key) {
if (key === Symbol.toPrimitive) return () => undefined;
if (!Object.keys(target).includes(key)) {
const proxy = new Proxy(exceptions, handler);
proxy.object = () => key;
return proxy;
}
return target[key];
},
}
export default new Proxy({}, handler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment