Skip to content

Instantly share code, notes, and snippets.

@aal89
Last active October 17, 2018 12:53
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 aal89/5a252e4ccf941b63b1d6d20bb72d6366 to your computer and use it in GitHub Desktop.
Save aal89/5a252e4ccf941b63b1d6d20bb72d6366 to your computer and use it in GitHub Desktop.
One line utility function to determine if a certain key or a point separated key list exists on any given object for Javascript. Also accounts for empty strings and all other falsey values.
// Regular Javascript version (in the end we have to evaluate the return into the proper boolean, an empty string is
// falsey in Javascript, but in this case we want it to behave as truthy. The OR operator with: '|| 1' is there to 'cast'
// false property values into a truthy value.
var keyExistsOn = (o, k) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;
// Curried Javascript version, with the same boolean evaluation at the end.
var keyExistsOn = (k) => (o) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;
// OUTPUT
var obj = {
test: "",
locals: {
test: "",
test2: false,
test3: NaN,
test4: 0,
test5: undefined,
auth: {
user: "hw"
}
}
}
keyExistsOn(obj, "")
> false
keyExistsOn(obj, "locals.test")
> true
keyExistsOn(obj, "locals.test2")
> true
keyExistsOn(obj, "locals.test3")
> true
keyExistsOn(obj, "locals.test4")
> true
keyExistsOn(obj, "locals.test5")
> true
keyExistsOn(obj, "sdsdf")
> false
keyExistsOn(obj, "sdsdf.rtsd")
> false
keyExistsOn(obj, "sdsdf.234d")
> false
keyExistsOn(obj, "2134.sdsdf.234d")
> false
keyExistsOn(obj, "locals")
> true
keyExistsOn(obj, "locals.")
> false
keyExistsOn(obj, "locals.auth")
> true
keyExistsOn(obj, "locals.autht")
> false
keyExistsOn(obj, "locals.auth.")
> false
keyExistsOn(obj, "locals.auth.user")
> true
keyExistsOn(obj, "locals.auth.userr")
> false
keyExistsOn(obj, "locals.auth.user.")
> false
keyExistsOn(obj, "locals.auth.user")
> true
@aal89
Copy link
Author

aal89 commented Oct 17, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment