Skip to content

Instantly share code, notes, and snippets.

@Artem-Schander
Last active December 21, 2018 18:49
Show Gist options
  • Save Artem-Schander/c485b3b11a3b347d0e7eeb04e57003bd to your computer and use it in GitHub Desktop.
Save Artem-Schander/c485b3b11a3b347d0e7eeb04e57003bd to your computer and use it in GitHub Desktop.
Enhanced _.get

Lodash _.get enhanced with * wildcard

See in action jsfiddle

let collection = [];
_.mixin({
'enhancedGet': function(object, path, defaultValue) {
let result, parts = path.split('*');
if (parts.length <= 1) {
result = _.get(object, path, defaultValue);
} else {
path = _.trim(parts.shift(), '.');
let remainingPath = _.trim(parts.join('*'), '.');
let data = object
if (path) data = _.get(object, path)
if (data && data.length) {
data.forEach(item => {
const nextLevelResult = _.enhancedGet(item, remainingPath, defaultValue);
if (parts.length == 1) collection.push(nextLevelResult);
})
}
result = _.compact(collection);
collection = [];
}
return result;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment