I've been diving into the world of array of objects and have successfully flattened them. Now I'm faced with the challenge of nesting them based on unique values at different levels. Currently, I'm using the reduce method to achieve this, but I end up getting new objects for each entry.
data = [
{ name1 : 'Tennis', id1: 1, name2: 'ATP', id2: 2, name3: 'Men Singles', id3: 4},
{ name1 : 'Tennis', id1: 1, name2: 'ATP', id2: 2, name3: 'Men Singles', id3: 4},
{ name1 : 'Tennis', id1: 1, name2: 'ATP', id2: 2, name3: 'Men Doubles', id3: 5},
{ name1 : 'Tennis', id1: 1, name2: 'WTA', id2: 3, name3: 'Women Doubles', id3: 6},
{ name1 : 'Tennis', id1: 1, name2: 'WTA', id2: 3, name3: 'Women Singles', id3: 7}
]
Desired result:
result: [
{ sport: 'Tennis',
league:
[{
ATP: [{ event: 'Men Singles', 'Men Doubles' }],
WTA: [{ event: 'Women Singles', 'Women Doubles' }]
}]
}]
Current code snippet:
const result = data.reduce((arr, item) => {
if (arr.indexOf(item.name1) === -1) {
arr.push({
sport: item.name1 ,
league: item.name2 ,
event: item.name3
})
}
return arr;
}, [])
The issue is that I'm getting every value individually like so:
0: {sportName: 'Tennis', league: 'ATP', event: 'Men Singles'}
1: {sportName: 'Tennis', league: 'WTA', event: 'Women Doubles'}
2: {sportName: 'Tennis', league: 'WTA', event: 'Women Doubles'}
.... etc
How can I modify my approach to obtain a single nested object as desired? I'm feeling quite stuck at the moment.