Last active
April 15, 2020 20:23
-
-
Save olayemii/948e5f611ee3f83e811d0040a2f0c4d4 to your computer and use it in GitHub Desktop.
A simple helper function for getting deeply nested object property
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
const getObjectProperty = (obj, path, defaultValue="", returnUndefined=true) => { | |
const checkForDefaultValue = value => | |
value !== undefined ? value : undefined; | |
if (path === undefined) { | |
return obj; | |
} | |
try { | |
const value = path.split('.').reduce((o, i) => o[i], obj); | |
if (value === undefined && returnUndefined) return value; | |
return value !== undefined ? value : checkForDefaultValue(defaultValue); | |
} catch (e) { | |
if (e instanceof TypeError) return checkForDefaultValue(defaultValue); | |
throw e; | |
} | |
}; | |
/* | |
const a = { | |
b: { | |
c: [ | |
{ | |
d: { | |
e: 14 | |
} | |
}, | |
[16, 11] | |
], | |
d: 12 | |
} | |
}; | |
getObjectProperty(a, 'b.d', "Default!"); | |
// 12 | |
getObjectProperty(a, 'b.e', "Not a property"); | |
// undefined | |
getObjectProperty(a, 'b.e', "Not a property", false); | |
// Not a property | |
getObjectProperty(a, 'b.c.0.d.e', "Not a property!"); | |
// 14 | |
getObjectProperty(a, 'b.c.1.0', "Not a property!"); | |
//16 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ahkohd okay, I added a flag to allow undefined returns or fall back to a set default value, I also included your example. 👌🏾