lodash 的 _.invertBy() 的反函数
Inverse function of lodash's _.invertBy()
lodash 的_.invertBy()
方法的反函数是什么?
我想做一个往返并在反转之后将对象转换为相同的形式。但如果我这样做
> _.invertBy({apple: 'fruit', pear: 'fruit'})
{ fruit: [ 'apple', 'pear' ] }
> _.invertBy({ fruit: [ 'apple', 'pear' ] })
{ 'apple,pear': [ 'fruit' ] }
和{ 'apple,pear': [ 'fruit' ] }
与{apple: 'fruit', pear: 'fruit'}
不同。
你可以从 github 破解 invertBy
的源代码并想出类似
的东西
function invertBackBy(object, iteratee = _.identity) {
const result = {}
Object.keys(object).forEach((key) => {
object[key].map(iteratee).forEach((value) => {
result[value] = key
})
})
return result
}
或者如果你想要一个 lodash one-liner,我认为没有比
更简单的了
oinv => _.reduce(oinv, (acc, values, key) =>
_.assign(acc, _.fromPairs(_.map(values, value => [value, key]))), {})
参见 fiddle 示例。
lodash 的_.invertBy()
方法的反函数是什么?
我想做一个往返并在反转之后将对象转换为相同的形式。但如果我这样做
> _.invertBy({apple: 'fruit', pear: 'fruit'})
{ fruit: [ 'apple', 'pear' ] }
> _.invertBy({ fruit: [ 'apple', 'pear' ] })
{ 'apple,pear': [ 'fruit' ] }
和{ 'apple,pear': [ 'fruit' ] }
与{apple: 'fruit', pear: 'fruit'}
不同。
你可以从 github 破解 invertBy
的源代码并想出类似
function invertBackBy(object, iteratee = _.identity) {
const result = {}
Object.keys(object).forEach((key) => {
object[key].map(iteratee).forEach((value) => {
result[value] = key
})
})
return result
}
或者如果你想要一个 lodash one-liner,我认为没有比
更简单的了oinv => _.reduce(oinv, (acc, values, key) =>
_.assign(acc, _.fromPairs(_.map(values, value => [value, key]))), {})
参见 fiddle 示例。