Skip to content

Instantly share code, notes, and snippets.

@Oliboy50
Last active May 8, 2018 14:40
Show Gist options
  • Save Oliboy50/62ca0130c684a3645749b34bd2d2b0ee to your computer and use it in GitHub Desktop.
Save Oliboy50/62ca0130c684a3645749b34bd2d2b0ee to your computer and use it in GitHub Desktop.
Lodash multi get (with `[]` path syntax)
const _ = require('lodash');
function multiGet(object, path, defaultValue) {
return path
.split('[]')
.reduce((resolvedPaths, pathShard, pathShardIndex, pathShards) => {
const isFirstPathShard = pathShardIndex === 0;
const isLastPathShard = pathShardIndex === pathShards.length -1;
return resolvedPaths
.map(resolvedPath => {
const iterable = (resolvedPath || (pathShard && !isLastPathShard)) ? _.get(object, resolvedPath || pathShard) : object;
if (typeof iterable !== 'object') {
throw new Error('Given path does not match object structure.');
}
if (!Array.isArray(iterable) || pathShard.startsWith('[')) {
return [`${resolvedPath}${pathShard}`];
}
return iterable.map((e, i) => isFirstPathShard ? `${resolvedPath}${pathShard}[${i}]` : `${resolvedPath}[${i}]${pathShard}`);
})
.reduce((a, b) => a.concat(b))
;
}, [''])
.map(resolvedPath => _.get(object, resolvedPath, defaultValue))
;
}
console.log(
multiGet(
[
{
a: [
{
a: true,
},
{
a: true,
},
],
},
{
a: [
{
a: true,
},
{
b: true,
},
],
},
],
'[1].a[].a',
false
)
);
console.log(
multiGet(
{
a: [
{
a: true,
},
{
a: true,
},
],
},
'a[].a'
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment