Created
May 29, 2020 16:36
-
-
Save chrisgfortes/f075314799dcd4e5cd76af9482e315dc to your computer and use it in GitHub Desktop.
Deep diving in object to get a value (based on _.get from lodash)
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 stringToPath = (path) => { | |
const pattern = /\[([0-9]+)\]/g; | |
if (pattern.test(path)) return path.replace(pattern, '.$1').split('.'); | |
return path.split('.'); | |
}; | |
// First Approach: | |
const deepGet = (source, path, defaultValue) => { | |
const props = stringToPath(path); | |
if (source === undefined || source === null) return defaultValue; | |
if (props.length === 0) return obj; | |
const result = source[props[0]]; | |
const remainingPath = props.slice(1); | |
if(!remainingPath.length) return result; | |
return deepGet(result, remainingPath.join('.'), defaultValue); | |
} | |
// Second Approach: | |
const _deepGet = (source, path, defaultArgument) => { | |
return stringToPath(path).reduce((nestedObject, key) => { | |
return nestedObject && key in nestedObject ? nestedObject[key] : void 0; | |
}, source) || defaultArgument; | |
}; | |
const data = { | |
User: { | |
Profile: { | |
Address: [ | |
[{ Home: "Hello" }] | |
] | |
} | |
} | |
}; | |
console.log('First Approach:', deepGet(data, "User.Profile.Address[0][0].Home", "Default Value")); | |
console.log('Second Approach:', _deepGet(data, "User.Profile.Address[0][0].Home", "Default Value")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment