Last active
May 8, 2018 14:40
-
-
Save Oliboy50/62ca0130c684a3645749b34bd2d2b0ee to your computer and use it in GitHub Desktop.
Lodash multi get (with `[]` path syntax)
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
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