Reputation: 731
I have an array of Objects:
const array = [ {
"Type": "DefinedBenefitPension",
"Description": null,
"Year": 2016,
"Participants": 9.0,
"TotalAssets": 6668305.0,
"NetAssets": 6668305.0,
"PlanName": null
},
{
"Type": "DefinedContributionPension",
"Description": null,
"Year": 2016,
"Participants": 72.0,
"TotalAssets": 17230395.0,
"NetAssets": 17230395.0,
"PlanName": null
},
{
"Type": "DefinedBenefitPension",
"Description": null,
"Year": 2017,
"Participants": 7.0,
"TotalAssets": 2096999.0,
"NetAssets": 2096999.0,
"PlanName": null
}...
];
This is just a small piece of data. There are a lot of different types (not only DefinedBenefitPension
and DefinedContributionPension
).
I made an array with all unique types:
const uniquePensionTypes = data => {
const unique = [...new Set(data.map(plan => plan.Type))];
return unique;
};
Where I pass the original array as data. Now I need to divide Participants
and TotalAssets
as per same types. From this example I need to have arrays called definedBenefitPension
DefinedBenefitPensionParticipants = [9,7]
DefinedContributionPensionParticipants = [72]
How can I do that?
Upvotes: 1
Views: 80
Reputation: 322
If data
is the whole array of objects.
data.reduce( ( resObj, item ) => ({
...resObj,
[ item.Type ]: [
...( resObj[ item.Type ] || [] ),
item.Participants
]
}), {})
This will give you an object like
{
DefinedBenefitPension:[9,7],
DefinedContributionPension:[72]
}
Upvotes: 2