Skip to content

Instantly share code, notes, and snippets.

@jaibatrik
Last active July 10, 2020 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaibatrik/61fa4c9e0a64bd024db5dbcdac1d0799 to your computer and use it in GitHub Desktop.
Save jaibatrik/61fa4c9e0a64bd024db5dbcdac1d0799 to your computer and use it in GitHub Desktop.
Trace property access in nested JavaScript objects
const tracePropertyAccess = (obj, handler, path) => {
path = path || [];
return new Proxy(obj, {
get(target, propKey, receiver) {
const val = Reflect.get(target, propKey, receiver),
newPath = path.concat(propKey);
if (val && typeof val === 'object') {
return tracePropertyAccess(val, handler, newPath);
}
handler.call(null, newPath);
return val;
}
});
};
const testObj = { a: 1, b: { a: "no", b: "yes" }, c: { a: "green", b: { a: "blue", b: "orange" } } };

const tracer = tracePropertyAccess(testObj, console.log);

tracer.b.a; // Prints ["b", "a"]
tracer.a; // Prints ["a"]
tracer.c.c.a; // Prints ["c", "c"]
@jaibatrik
Copy link
Author

Thanks @NinaScholz for the snippet at StackOverflow.

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