【问题标题】:Inverse function of lodash's _.invertBy()lodash 的 _.invertBy() 的反函数
【发布时间】:2022-01-04 12:42:39
【问题描述】:

lodash的_.invertBy()方法的反函数是什么?

我想进行一次往返,然后在反转对象后将其转换为相同的形式。但是如果我这样做了

> _.invertBy({apple: 'fruit', pear: 'fruit'})
{ fruit: [ 'apple', 'pear' ] }
> _.invertBy({ fruit: [ 'apple', 'pear' ] })
{ 'apple,pear': [ 'fruit' ] }

{ 'apple,pear': [ 'fruit' ] }{apple: 'fruit', pear: 'fruit'} 不同。

【问题讨论】:

    标签: javascript object lodash


    【解决方案1】:

    人们可以从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 单线,我认为没有什么比

    简单得多了
    oinv => _.reduce(oinv, (acc, values, key) => 
       _.assign(acc, _.fromPairs(_.map(values, value => [value, key]))), {})
    

    请参阅fiddle 了解示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      相关资源
      最近更新 更多