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"]
Last active
July 10, 2020 12:41
-
-
Save jaibatrik/61fa4c9e0a64bd024db5dbcdac1d0799 to your computer and use it in GitHub Desktop.
Trace property access in nested JavaScript objects
This file contains hidden or 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
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; | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @NinaScholz for the snippet at StackOverflow.