Skip to content

Instantly share code, notes, and snippets.

@ilya-korotya
Last active May 31, 2018 06:53
Show Gist options
  • Save ilya-korotya/6324e5c6d347f3c6bc36477bcf173938 to your computer and use it in GitHub Desktop.
Save ilya-korotya/6324e5c6d347f3c6bc36477bcf173938 to your computer and use it in GitHub Desktop.
Check property in object
function proxyOptional(obj, evalFunc, def) {
const handler = {
get: function(target, prop, receiver) {
const res = Reflect.get(...arguments);
return typeof res === "object" ? proxify(res) : res != null ? res : def;
}
};
const proxify = target => {
return new Proxy(target, handler);
};
return evalFunc(proxify(obj, handler));
}
const obj = {
items: [{ hello: "Hello" }]
};
console.log(proxyOptional(obj, target => target.items[0].hello, "def")); // Prints Hello
console.log(proxyOptional(obj, target => target.items[0].hell, { a: 1 })); // Prinst { a: 1 }
// Analog without proxyOptional
console.log((obj && obj.items && obj.items[0] && obj.items[0].hello) || "def"); // Prints Hello
console.log((obj && obj.items && obj.items[0] && obj.items[0].hel) || "def"); // Prints def
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment