I'm attempting to organize a cleaner JSON object by grouping multiple objects with the same IDs. Here's my approach: 1. Save the ID of the first object and compare it with subsequent IDs. 2. Loop through the array to identify matching IDs. If found, create a new array of names in a separate object, otherwise add to a new object with the stored names as a property. 3. Clear out the names field.
There were various conditions to consider, especially when dealing with the last element in the array. I'm seeking an efficient solution for this task. Due to its specific nature, I haven't found a similar issue on Stack Overflow.
The initial JSON Object looks like this:
[
{
id: 1,
name: 'John'
},
{
id: 1,
name: 'Jack'
},
{
id: 2,
name: 'Drake'
},
{
id: 2,
name: 'Joey'
},
{
id: 3,
name: 'Justin'
},
{
id: 3,
name: 'Rob'
}
]
I aim to group similar IDs together, resulting in a structure like this:
[{
id: 1,
names: [{
name: 'John'
},
{
name: 'Jack'
}]
},
{
id: 2,
names: [{
name: 'Drake'
},
{
name: 'Joey'
}]
},
{
id: 3,
names: [{
name: 'Justin'
},
{
name: 'Rob'
}]
}]