Created
February 8, 2022 00:10
-
-
Save DavidWells/161ea0602511561ba26137ab0b56fddf to your computer and use it in GitHub Desktop.
Get nested prop values in JS proxy
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
| // via https://stackoverflow.com/questions/46005706/get-the-path-to-the-accessed-value-in-a-nested-object | |
| function wrap(o, fn, scope = []) { | |
| const handler = { | |
| set(target, prop, value, receiver) { | |
| fn('set value in scope: ', scope.concat(prop)) | |
| target[prop] = value | |
| return true | |
| }, | |
| get(target, prop, receiver) { | |
| fn('get value in scope: ', scope.concat(prop)) | |
| return target[prop] | |
| }, | |
| ownKeys() { | |
| fn('keys in scope: ', scope) | |
| return Reflect.ownKeys(o) | |
| } | |
| } | |
| return new Proxy( | |
| Object.keys(o).reduce((result, key) => { | |
| if (isObject(o[key])) { | |
| result[key] = wrap(o[key], fn, scope.concat(key)) | |
| } else { | |
| result[key] = o[key] | |
| } | |
| return result | |
| }, {}), | |
| handler | |
| ) | |
| } | |
| function isObject(obj) { | |
| return typeof obj === 'object' && !Array.isArray(obj) | |
| } | |
| const obj = wrap({ | |
| a0: { | |
| a1: { | |
| a2: 0 | |
| }, | |
| b1: { | |
| b2: 0 | |
| } | |
| }, | |
| b0: 0 | |
| }, console.log) | |
| // set value: | |
| obj.b0 = 1 | |
| // get value: | |
| console.log('value: ' + obj.a0.a1.a2) | |
| // list keys: | |
| console.log('keys: ', Object.keys(obj.a0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment