【问题标题】:Using lodash to zip two objects with keys from one and values from the other使用 lodash 压缩两个对象,其中一个对象的键和另一个对象的值
【发布时间】:2021-06-19 12:17:22
【问题描述】:

我有对象 AB 像这样:

const A = { a: 'foo', b: 'bar', c: 'baz' };
const B = { a: 'aaa', b: 'bbb', c: 'ccc' };

我需要将这两个转换为一个对象,其中键来自 A,值来自 B:

{ foo: 'aaa', bar: 'bbb', baz: 'ccc' }

如何用 lodash 做到这一点?

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    将对象转换为 [key, value] 对,展平为单个数组,然后按第一个元素(原始键)分组,将组映射到对数组,然后转换回对象。

    使用 lodash/fp:

    const { rest, flow, map, toPairs, flatten, groupBy, head, last, fromPairs } = _
    
    const fn = rest(flow(
      map(toPairs), // map each object to pairs of [key, value]
      flatten, // flatten to a single array of pairs
      groupBy(head), // group the pairs by the key
      map(map(last)), // create a new pair by taking the last element of each pair in the group
      fromPairs // convert to an object
    ))
    
    const A = { b: 'bar', c: 'baz', a: 'foo' }
    const B = { a: 'aaa', b: 'bbb', c: 'ccc' }
    
    const result = fn(A, B)
    
    console.log(result)
    <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

    使用 lodash:

    const { rest, flow, map, toPairs, flatten, groupBy, head, last, fromPairs } = _
    
    const fn = rest(flow(
      objs => map(objs, toPairs), // map each object to pairs of [key, value]
      flatten, // flatten to a single array of pairs
      pairs => groupBy(pairs, head), // group the pairs by the key
      groups => map(groups, group => map(group, last)), // create a new pair by taking the last element of each pair in the group
      fromPairs // convert to an object
    ))
    
    const A = { b: 'bar', c: 'baz', a: 'foo' }
    const B = { a: 'aaa', b: 'bbb', c: 'ccc' }
    
    const result = fn(A, B)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      • 2018-10-28
      • 2021-05-30
      • 2022-01-25
      • 2015-06-14
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多