I have an array of objects that looks like this:
[
{date: '2022-12-07', type: 'freeze', value: 3},
{date: '2022-12-06', type: 'freeze', value: 1},
{date: '2022-12-05', type: 'freeze', value: 1},
{date: '2022-12-04', type: 'boil', value: 1},
{date: '2022-12-04', type: 'freeze', value: 1},
{date: '2022-12-05', type: 'steam', value: 5}
]
I’d like to create an array of objects that combines all distinct types to become a key with the corresponding value for each distinct date so the types with no value in a given date will show as 0 with a total sum. The type(s) can vary from set to set, and I’d want only the found ones in the set to be present so the output looks like this:
This is a different question than what was raised here:
Most efficient method to groupby on an array of objects because part of what I’m looking to do is to turn all the values of the key ‘type’ into keys for each date with corresponding values as the value of the key. So this needs remapping along with grouping.
[
{date: '2022-12-04', freeze: 1, boil: 1, steam: 0, total: 2},
{date: '2022-12-05', freeze: 1, boil: 0, steam: 5, total: 6},
{date: '2022-12-06', freeze: 1, boil: 0, steam: 0, total: 1},
{date: '2022-12-07', freeze: 3, boil: 0, steam: 0, total: 3}
]
2
Answers
This is another method suggested by @cmgchess that works well, and enables dynamic keys.
If we break it down, you could achieve the result by;
type
andtotal
.