Last active
June 4, 2018 15:45
-
-
Save condef5/f5deefb2bf22c0f3e110352bd4621224 to your computer and use it in GitHub Desktop.
Function Path for crehana ๐ผ
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 getIn = (obj, path, defaultValue) => { | |
| var _path = path.split('.'); | |
| var _obj = Object.assign({}, obj); | |
| var head; | |
| while(typeof _obj == 'object' && _path.length > 0) { | |
| [head, ..._path] = _path; | |
| _obj = _obj[head]; | |
| } | |
| return _obj || defaultValue; | |
| } | |
| var object = { 'a': [{ 'b': { 'c': 3 } }], 'b': [{a: 'a'}] }; | |
| console.log(getIn(object, 'a.b.c', 'default')); | |
| // => 'default' | |
| var object2 = {a: { b: { c: 3 } } }; | |
| console.log(getIn(object2, 'a.b.c', 5)); | |
| // => 3 | |
| console.log(getIn(object2, 'a.b.d', 5)); | |
| // => 5 | |
| // Credits @gilesbradshaw => destructuring is insane => https://gist.github.com/mikaelbr/9900818 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update code for this case: