What is the inverse function of lodash's _.invertBy()
method?
I want to do a roundtrip and convert an object later to the same form after inverting it. But if I do
> _.invertBy({apple: 'fruit', pear: 'fruit'})
{ fruit: [ 'apple', 'pear' ] }
> _.invertBy({ fruit: [ 'apple', 'pear' ] })
{ 'apple,pear': [ 'fruit' ] }
and { 'apple,pear': [ 'fruit' ] }
is not the same as {apple: 'fruit', pear: 'fruit'}
.
CodePudding user response:
One can hack the the source code of invertBy
from github and come up with something like
function invertBackBy(object, iteratee = _.identity) {
const result = {}
Object.keys(object).forEach((key) => {
object[key].map(iteratee).forEach((value) => {
result[value] = key
})
})
return result
}
or if a lodash one-liner is what you wanted, I think there's nothing much simpler than
oinv => _.reduce(oinv, (acc, values, key) =>
_.assign(acc, _.fromPairs(_.map(values, value => [value, key]))), {})
see fiddle for an example.