Let's say I have an array that looks like this:
[
{ id 1, date: "1/1/2021", count: 2, oldCount: 1 },
{ id 1, date: "2/1/2021", count: 3, oldCount: 2 },
{ id 2, date: "1/1/2021", count: 2, oldCount: 1 },
{ id 2, date: "2/1/2021", count: 3, oldCount: 2 }
]
The real key here is the combination of id and date. I want the final result to look like this:
[
{ id 1, "1/1/2021": 2, "2/1/2021": 3, "1/1/2021_old": 1, "2/1/2021_old": 2 },
{ id 2, "2/1/2021": 3, "2/1/2021": 3, "1/1/2021_old": 1, "2/1/2021_old": 2 }
]
I'd prefer to use lodash for this. The part that hangs me up is the additional properties to add to each object in the array. In our real world scenario, there could be several thousand records that need to be deduped and mapped, and this is resource intensive.
You can see the logic. It's grouping by id, and adding a property name based on the value of the original date property.
Here's a non-working example of my desired functionality:
arr = _.map(_.groupBy(data, "id"), objs => {
return _.assignWith({ /* I don't know the dates to set the property names */ }, ...objs)
});
I can do this with nested loops. I'm looking for best performance options and less lines of code.