Problem with keyBy in lodash. Lodash removed some properties

Viewed 247

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?

1 Answers

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>

Related