I have an array of objects. I need to combine all the objects on the array that have the same key.
This is the original array:
const original = [
{ Country: 'Asia', Year: 2021, Month: 'January', Sport: 'Football' },
{ Country: 'Asia', Year: 2021, Month: 'March', Sport: 'Basketball' },
{ Country: 'Asia', Year: 2022, Month: 'May', Sport: 'Basketball' },
{ Country: 'Europe', Year: 2022, Month: 'June', Sport: 'Basketball' },
{ Country: 'Europe', Year: 2022, Month: 'October', Sport: 'Volley' },
];
I need to combine the objects so the output is as follows:
const result = [
{
code: 'AS',
name: 'Asia',
childs: [
{
code: 'AS_2021',
name: '2021',
childs: [
{ code: 'AS_2021_January', name: 'January', childs: [{ code: 'AS_2021_January_Football', name: 'Football' }] },
{ code: 'AS_2021_March', name: 'March', childs: [{ code: 'AS_2021_March_Basketball', name: 'Basketball' }] },
],
},
{
code: 'AS_2022',
name: '2022',
childs: [{ code: 'AS_2022_May', name: 'May', childs: [{ code: 'AS_2022_May_Basketball', name: 'Basketball' }] }],
},
],
},
{
code: 'EU',
name: 'Europe',
childs: [
{
code: 'EU_2022',
name: '2022',
childs: [
{ code: 'EU_2022_June', name: 'June', childs: [{ code: 'EU_2022_June_Basketball', name: 'Basketball' }] },
{ code: 'EU_2022_October', name: 'October', childs: [{ code: 'EU_2022_October_Volley', name: 'Volley' }] },
],
},
],
},
];