그래서 나는 그룹화하려는 객체의 배열을 가지고 있습니다. 저는 여전히 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');
});
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다