Skip to content

Instantly share code, notes, and snippets.

View ashish-r's full-sized avatar
🏠
Working from home

Ashish Ranjan ashish-r

🏠
Working from home
View GitHub Profile
@ashish-r
ashish-r / nestedObjValue.js
Last active April 3, 2019 17:30
Safely access value from a nested object
//Param1: Nested Object
//Param2: Array of keys in the desired order
//Return: Final value from given object based on the given key order if exists, else undefined
function nestedObjValue(obj, keyOrder){
return keyOrder.reduce((a,b) => typeof a !== 'object' || !a ? undefined : a[b] , obj)
}
//Examples
nestedObjValue({a: {b: {c : {d: {e: 3}}}}}, ['a','b', 'c', 'd', 'e']) //3