Created
March 17, 2020 02:03
-
-
Save crates/5385bd15be9e6613b5150afac286ccd2 to your computer and use it in GitHub Desktop.
Wrap your JS objects in a Proxy so that you can safely access their properties (ES2015+)
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 proxyObj = (obj) { | |
return new Proxy(obj, { | |
get: function(target, name) { | |
const result = target[name]; | |
if (!!result) { | |
return (result instanceof Object)? proxyObj(result) : result; | |
} | |
return proxyObj({}); | |
} | |
}); | |
}; | |
// Usage: | |
const jane = { | |
name: 'Jane', | |
age: 35 | |
}; | |
const john = { | |
name: 'John', | |
address: { | |
street: '7th Avenue', | |
city: 'Ecmaville', | |
zipCode: '23233' | |
}, | |
sister: jane, | |
age: 28 | |
}; | |
var proxyPerson = proxyObj(john); | |
console.log(proxyPerson.name); // --> "John" | |
console.log(proxyPerson.address.street); // --> "7th Avenue" | |
console.log(proxyPerson.sister.name); // --> "Jane" | |
console.log(proxyPerson.sister.address); // --> {} | |
console.log(proxyPerson.sister.address.street); // --> {} | |
// See also: | |
// https://gist.github.com/dakaraphi/6a87168db66fd8f032d2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment