Skip to content
Advertisement

How to combine all objects into one based on key

Here is the scenario I am looking at:

I want to reduce these objects

JavaScript

and I found a solution that adds their values:

JavaScript

which results to:

JavaScript

And now my problem is I don’t know yet how to work this around to have my expected output which if isRefund is true, it must be subtracted instead of being added, retain the vendor_id and also the concatenated date instead of only one entry date:

JavaScript

I will accept and try to understand any better way or workaround for this. Thank you very much.

Advertisement

Answer

As you want custom behaviour for several fields, and don’t need the recursive aspect of the merge, I would suggest you create a custom merge function, specific to your business logic:

JavaScript

You could also reintroduce the isRefund property in the result for when the total amount turns out to be negative (only do this when data.length > 1 as otherwise result is just the original single object in data):

JavaScript

Distinct results for different dates and/or vendors

Then use a “dictionary” (plain object or Map) keyed by date/vendor combinations, each having an aggregating object as value.

To demonstrate, I added one more object in the data that has a different date and amount of 300:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement