VanillaJS中对象数组上的多级组



所以我有一个对象数组,我正在尝试将它们组合在一起,我对JS还是有点陌生,随着我练习的越来越多,我变得越来越好,但还不太好,无论如何,我正在努力找出如何在多个级别上进行分组。例如,如果我有一组主题公园,我想按州和城市分组。我可以按州分组,也可以按城市分组,但我对按州分组和按城市分组有点迷失了方向。

let parks = [{
id: 546,
name: "Kalahari Resorts",
city: "Wisconsin Dells",
state: "Wisconsin",
country: "United States"
},
{
id: 547,
name: "Little Amerricka",
city: "Marshall",
state: "Wisconsin",
country: "United States"
},
{
id: 2,
name: "Calaway Park",
city: "Calgary",
state: "Alberta",
country: "Canada"
}
];
function groupBy(objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
let group = groupBy(parks, 'state');
console.log(group);

但我想做的是,首先按州对所有内容进行分组,如上所述,然后按城市进行分组,我正试图在没有库的情况下做到这一点,只是简单的Vanilla JS

所以我应该得到

{
Alberta: Calgary: []
}, {
Wisconsin: Wisconsin Dells: [],
Marshall: []
}

您可以在此处重用groupBy函数:

let group = groupBy(parks, 'state');
Object.keys(group).forEach(stateKey => {
group[stateKey] = groupBy(group[stateKey], 'city');
// For further grouping, just make sure you pass in an array
// as the first argument to groupBy. 
Object.keys(group[stateKey]).forEach(cityKey => {
group[stateKey][cityKey] = groupBy(group[stateKey][cityKey], 'county');
});
});

最新更新