I'm looking for a best practice on how to group an array by the object's associated ID. The data looks like this:
const data = [
{
"id": 1,
"association": {
"id": 1,
"name": "Association A"
},
"more_data": "...",
...
},
{
"id": 2,
"association": {
"id": 2,
"name": "Association B"
},
...
},
...
]
So the result would return:
{
1: [ { data_hash }, { data_hash }, ...],
2: [ { data_hash }, { data_hash }, ...],
...
}
Where 1 and 2 are the association IDs above. Ruby/Rails has built in methods to do this easily:
Data.group_by(&:association_id).each do |association_id, data|
puts association_id
data.each do |data|
puts data
end
end
Is there something similar or equivalent in the JavaScript/ES6 world, or can anyone offer some insight on how to best handle this? A library, or even just a function that would do the trick?
The other added challenge here is that the association's ID sits in that nested hash.
EDIT: Not opposed to using a library at all. Looking for recommendations for something lightweight.