简体   繁体   中英

Problem with keyBy in lodash. Lodash removed some properties

I have an array for example

let arr = [{a:1, b:2, c:3}, {a:1, b:2}, {a:2, c:3}, {a:2, c:3} ];

and I used the keyBy function

const f = _.keyBy(arr, e => e.a);

Result is

1: {a: 1, b: 2}
2: {a: 2, c: 3}

But I need all properties, the result I expected is

1: {a: 1, b: 2, c:3}
2: {a: 2, c: 3}

What I have to do?

Group the items by a , and the use _.mapValues() to iterate the group, and merge each group to a single object:

 const arr = [{a:1, b:2, c:3}, {a:1, b:2}, {a:2, c:3}, {a:2, c:3} ]; const result = _.mapValues( _.groupBy(arr, 'a'), group => _.merge({}, ...group) ) 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>

With lodash/fp you can create a terser function using the same idea:

 const { flow, groupBy, mapValues, mergeAll } = _ const fn = flow( groupBy('a'), mapValues(mergeAll), ) const arr = [{a:1, b:2, c:3}, {a:1, b:2}, {a:2, c:3}, {a:2, c:3} ]; const result = fn(arr) console.log(result)
 <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM