简体   繁体   English

Vanilla JS 中对象数组的多级组

[英]Multi level group on array of objects in Vanilla JS

So I have an array of objects that I am trying to group together, I'm still kinda new to JS, getting better as I practice more and more but not great yet, anyway I'm trying to figure out how to group at multiple levels.所以我有一组我想组合在一起的对象,我对 JS 还是有点陌生​​,随着我练习的越来越多,但还不是很好,无论如何我想弄清楚如何组合多个水平。 For example if I have a group of theme parks that I wanted to group by state and then city.例如,如果我有一组主题公园,我想按州然后按城市分组。 I can get the group by state, I can get the group by city, but I'm a little lost on group by state and city.我可以按州获得组,我可以按城市获得组,但我对按州和城市的组有点迷茫。

 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);

But what I want to do is have it first group everything by state, which the above does, and then group by city, and I'm trying to do this without libraries, just plain Vanilla JS但是我想要做的是首先按州对所有内容进行分组,上面这样做,然后按城市分组,我试图在没有图书馆的情况下做到这一点,只是普通的 Vanilla JS

So I should get所以我应该得到

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

You can just reuse your groupBy function here:您可以在此处重用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');
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM