Created
April 8, 2015 20:40
-
-
Save miguelludert/5b4c5ef8efa996ee510a to your computer and use it in GitHub Desktop.
lodash getset
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
(function(_){ | |
function makePath(path){ | |
return path.replace(/\[(["']?)([^\1]+?)\1?\]/g, '.$2').replace(/^\./, '').split('.'); | |
}; | |
_.mixin({ | |
get: function (obj, path, defaultValue) { | |
if (_.isString(path)) { | |
path = split(path); | |
} | |
// end of the line (found nothing) | |
if (obj === undefined) { | |
return defaultValue; | |
} | |
// end of the line (found self) | |
if (path.length === 0) { | |
return obj; | |
} | |
// can't continue down the line any further (non-traversable) | |
if (obj === null) { | |
return defaultValue; | |
} | |
// keep traversing | |
return _.get(obj[_.first(path)], _.rest(path), defaultValue); | |
}, | |
set : function (obj, path, value) { | |
if (_.isString(path)) { | |
path = split(path); | |
} | |
// can't continue down the line any further (non-traversable) | |
if (obj === null || obj === undefined) { | |
return; | |
} | |
// end of the line (found self) | |
if (path.length === 1) { | |
return obj[path[0]] = value; | |
} | |
// keep traversing | |
_.set(obj[_.first(path)], _.rest(path), value); | |
} | |
}); | |
}(_)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment