将具有相同键的对象组合/分组,并将其应用于子对象



我有一个对象数组。我需要组合数组中具有相同键的所有对象。

这是原始阵列:

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' },
];

我需要组合对象,这样输出如下:

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' }] },
],
},
],
},
];

您可以在original数组的元素上循环,并继续推送新对象或更新现有对象(如果存在(。不确定如何生成code,因为您还没有解释过,但这是result数组的其余部分:

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'
},
];
var result = [];
for (let element of original) {
let existingCountry = result.find(ele => ele.name == element.Country)
if (existingCountry) {
let existingYear = existingCountry.children.find(ele => ele.name == element.Year);
if (existingYear) {
let existingMonth = existingYear.children.find(ele => ele.name == element.Month)
if (existingMonth) {
existingMonth.children.push({
name: element.Sport
})
} else {
existingYear.children.push({
name: element.Month,
children: [{
name: element.Sport
}]
})
}
} else {
existingCountry.children.push({
name: element.Year,
children: [{
name: element.Month,
children: [{
name: element.Sport
}]
}]
})
}
} else {
result.push({
name: element.Country,
children: [{
name: element.Year,
children: [{
name: element.Month,
children: [{
name: element.Sport
}]
}]
}]
})
}
}
console.log(result)

最新更新