'Combine children where parent keys are the same in a array of objects

I have an array of objects with duplicate parent keys:

[
    {parent1: {'child_id_1': 'value_child_1'}}
    {parent1: {'child_id_1_1': 'value_child_1_1'}}
    {parent2: {'child_id_2_1': 'value_child_2_1'}}
    {parent2: {'child_id_2_2': 'value_child_2_2'}}
    {parent2: {'child_id_2_3': 'value_child_2_3'}}
    ...
]

And I'm looking for this result:

[
    {parent1: {'child_id_1': 'value_child_1'}, {'child_id_1_1': 'value_child_1_1'}}
    {parent2: {'child_id_2_1': 'value_child_2_1'}, {'child_id_2_2': 'value_child_2_2'}, {'child_id_2_3': 'value_child_2_3'}}
]

I've tried something similar to this below but it only returns one key pair.

const unique = Array.from(new Set(filteredViews.map(a => a.id)))
   .map(id => {
       return filteredViews.find(a => a.view_name === id)
})

Any help would be greatly appreciated!



Solution 1:[1]

Assuming your data looks like this:

const data = [
  {parent1: {'child_id_1': 'value_child_1'}},
  {parent1: {'child_id_1_1': 'value_child_1_1'}},
  {parent2: {'child_id_2_1': 'value_child_2_1'}},
  {parent2: {'child_id_2_2': 'value_child_2_2'}},
  {parent2: {'child_id_2_3': 'value_child_2_3'}},
]

Using a vanilla approach you could do:

let unique = {};

data.forEach(d => {
  let key = Object.keys(d)[0]; // assuming your object has a single key
  if (!unique[key]) { unique[key] = []; }
  unique[key].push(d[key]);
});

Resulting in:

{
  "parent1": [
     {"child_id_1":"value_child_1"}, 
     {"child_id_1_1":"value_child_1_1"}
  ],
  "parent2": [
     {"child_id_2_1":"value_child_2_1"},
     {"child_id_2_2":"value_child_2_2"},
     {"child_id_2_3":"value_child_2_3"}
  ]
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vinicius Stramosk