Skip to content

Instantly share code, notes, and snippets.

@eeropic
Created September 25, 2019 18:42
Show Gist options
  • Save eeropic/2742be1f1e03d94a7d1bc558ef1645b6 to your computer and use it in GitHub Desktop.
Save eeropic/2742be1f1e03d94a7d1bc558ef1645b6 to your computer and use it in GitHub Desktop.
nested object proxy handler from Michał Perłakowski & James Coyle at https://stackoverflow.com/questions/41299642/how-to-use-javascript-proxy-for-nested-objects
const handler = {
get(target, key) {
if (key == 'isProxy')
return true;
const prop = target[key];
if (typeof prop == 'undefined')
return;
if (!prop.isProxy && typeof prop === 'object')
target[key] = new Proxy(prop, handler);
return target[key];
},
set(target, key, value) {
console.log('Setting', target, `.${key} to equal`, value);
target[key] = value;
return true;
}
};
var test = {
string: "data",
number: 231321,
object: {
string: "data",
number: 32434,
nested: {
prop1: 1,
prop2: 2
}
},
array: [
1, 2, 3, 4, 5
],
};
test = new Proxy (test, handler);
test.number=123
test.object.string = "keke"
test.object.nested.prop1 = 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment