Created
June 14, 2018 18:38
-
-
Save paolaozv/73c7658d6311ecb7c7516c8c722aa644 to your computer and use it in GitHub Desktop.
function getIn
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
| const a = getIn(obj, path, defaultValue) | |
| Ejemplo: | |
| let object = { 'a': [{ 'b': { 'c': 3 } }] }; | |
| getIn(object, 'a.b.c', 'default'); | |
| // => 'default' | |
| let object2 = {a: { b: { c: 3 } } }; | |
| getIn(object2, 'a.b.c', 5); | |
| // => 3 | |
| getIn(object2, 'a.b.d', 5) ; | |
| // => 5 | |
| function getIn(obj, path, defaultValue) { | |
| var result = path. | |
| split('.'). | |
| reduce((last, current) => (last || {})[current], obj); | |
| console.log(path, path.split('.').reduce((last, current) => {console.log(last, current, (last || {})[current])})); | |
| if (result === undefined) return defaultValue; | |
| else return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment