Last active
October 17, 2018 12:53
-
-
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.
This file contains 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
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See this NPM package: https://www.npmjs.com/package/has-deep-value