Last active
April 3, 2019 17:30
-
-
Save ashish-r/91ee6ad307687061b765dcf32de40589 to your computer and use it in GitHub Desktop.
Safely access value from a nested object
This file contains hidden or 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
//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 |
Just check null condition to make this function more versatile and robust. Good one Ashish !
@cw-patiltejashree gist updated, thanks for the suggestion.
@balsikandar glad it helped.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice example man. I have been trying to do the same and your help came at the right moment