lodash_.invertBy()方法的反函式是什么?
我想做一個往返并在反轉物件后將其轉換為相同的形式。但如果我這樣做
> _.invertBy({apple: 'fruit', pear: 'fruit'})
{ fruit: [ 'apple', 'pear' ] }
> _.invertBy({ fruit: [ 'apple', 'pear' ] })
{ 'apple,pear': [ 'fruit' ] }
和{ 'apple,pear': [ 'fruit' ] }不一樣{apple: 'fruit', pear: 'fruit'}。
uj5u.com熱心網友回復:
可以破解invertBy來自github的源代碼并想出類似的東西
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]))), {})
參見小提琴示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366835.html
標籤:javascript 目的 洛达什
