Skip to content

Instantly share code, notes, and snippets.

@ashish-r
Last active April 3, 2019 17:30
Show Gist options
  • Save ashish-r/91ee6ad307687061b765dcf32de40589 to your computer and use it in GitHub Desktop.
Save ashish-r/91ee6ad307687061b765dcf32de40589 to your computer and use it in GitHub Desktop.
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
nestedObjValue({a: {b: {c : {d: {e: 3}}}}}, ['a','b', 'c', 'f', 'g']) //undefined
nestedObjValue({a: {b: {c : {d: {e: [{a: 3}, {b: 4}]}}}}}, ['a','b', 'c', 'd', 'e', 1, 'b']) //4
nestedObjValue({a: {b: {c : {d: {e: [{a: 3}, {b: 4}]}}}}}, ['a','b', 'c', 'd', 'e', 0, 'b']) //undefined
@balsikandar
Copy link

balsikandar commented Aug 8, 2018

Nice example man. I have been trying to do the same and your help came at the right moment

@cw-patiltejashree
Copy link

Just check null condition to make this function more versatile and robust. Good one Ashish !

@ashish-r
Copy link
Author

ashish-r commented Aug 8, 2018

@cw-patiltejashree gist updated, thanks for the suggestion.

@ashish-r
Copy link
Author

ashish-r commented Aug 8, 2018

@balsikandar glad it helped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment