Skip to content

Instantly share code, notes, and snippets.

@doliG
Last active February 28, 2020 09:53
Show Gist options
  • Select an option

  • Save doliG/191744879858b2c09003a7ce65d6e06f to your computer and use it in GitHub Desktop.

Select an option

Save doliG/191744879858b2c09003a7ce65d6e06f to your computer and use it in GitHub Desktop.
/**
* Extending object method with isDefined()
* @param {string} keysAsString Kets you want to check
* @return {boolean} Return true if object.keys exist, false otherwise
*
* Example :
* const fruitSalad = {
* strawberry: {
* apple: {
* pear: "Wtf",
* },
* },
* };
*
* fruitSalad.isDefined("strawberry.apple.pear") // Return true
* fruitSalad.isDefined("strawberry.pinapple") // Return false
*/
Object.defineProperty(Object.prototype, 'isDefined', {
value: function(keysAsString: string) {
const keys = keysAsString.trim().split(".");
let browsable = this;
let i = 0;
for (i; browsable[keys[i]] != undefined; i++) {
browsable = browsable[keys[i]];
}
return (i == keys.length);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment