See in action jsfiddle
Last active
December 21, 2018 18:49
-
-
Save Artem-Schander/c485b3b11a3b347d0e7eeb04e57003bd to your computer and use it in GitHub Desktop.
Enhanced _.get
This file contains 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
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