Skip to content

Instantly share code, notes, and snippets.

@condef5
Last active June 4, 2018 15:45
Show Gist options
  • Save condef5/f5deefb2bf22c0f3e110352bd4621224 to your computer and use it in GitHub Desktop.
Save condef5/f5deefb2bf22c0f3e110352bd4621224 to your computer and use it in GitHub Desktop.
Function Path for crehana 🗼
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
@condef5
Copy link
Author

condef5 commented Jun 4, 2018

Update code for this case:

var object = {a: { b: { c: 3 } } };     
console.log(getIn(object, 'a.b', 5));
// => { c: 3 }

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