Skip to content

Instantly share code, notes, and snippets.

@cyrilf
Last active June 21, 2018 12:38
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 cyrilf/ab6ffe82eaf9f75f7f473641ab48af68 to your computer and use it in GitHub Desktop.
Save cyrilf/ab6ffe82eaf9f75f7f473641ab48af68 to your computer and use it in GitHub Desktop.
Proxy
// From: https://stackoverflow.com/questions/50963215/can-we-specify-a-generic-getter-on-an-object-in-javascript
// Allows you to access nested property (1 level) without the need to to safety check
const properties = { email: { title: "Email", value: "xyz@gh.com" } }
const proxy = new Proxy(properties, {
get: (target, prop) => (prop in target) ? target[prop] : {},
})
// or
const proxy = new Proxy(properties, {
get: (target, prop) => {
if (prop in target) {
let ret = Reflect.get(target, prop)
if (typeof ret === "function") {
ret = ret.bind(target)
}
return ret
}
return {}
},
})
proxy.email.value === "xyz@gh.com" // true
properties.unknownProp.value === Error // cannot read `value` of undefined
properties.unknownProp && properties.unknownProp.value === undefined // true / it works but long to write..
proxy.unknownProp.value === undefined // true / short, clean & safe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment