Get Values from Nested Objects

JavaScriptPosted on

When we are working with nested objects, many times we want to retrieve a single value what is deeply stored in the object.

If we don’t need the complexity of lodash’s get library, we use this little snippet:

 * Get the value from an object by the given key.
 * example: get('a.b', {a: {b: c}}, 'default value')
function get(key, object, def = null)
    return key.toString().split('.').reduce((t, i) => t[i] || def, object);

Need a web developer? Maybe we can help, get in touch!

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Similar Posts

More content in JavaScript category