[英]Using lodash to zip two objects with keys from one and values from the other
I have objects A
and B
like this:我有这样的对象
A
和B
:
const A = { a: 'foo', b: 'bar', c: 'baz' };
const B = { a: 'aaa', b: 'bbb', c: 'ccc' };
I need to transform these two into an object with keys from A and values from B:我需要将这两个转换为一个对象,其键来自 A,值来自 B:
{ foo: 'aaa', bar: 'bbb', baz: 'ccc' }
How can I do this with lodash?我怎样才能用 lodash 做到这一点?
Convert the objects into pairs of [key, value]
, flatten to a single array, then group by the 1st element (the original key), map the groups to an array of pairs, and convert back to an object.将对象转换为
[key, value]
,展平为单个数组,然后按第一个元素(原始键)分组,将组映射到成对数组,然后转换回对象。
Using lodash/fp:使用 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>
Using lodash:使用 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.