반응형
계산된 개체와 배열의 두 필드별 정렬
다음 형식으로 데이터를 반환하는 API에서 정보를 가져옵니다.
[
{
"id": 173,
"date": "2020-12-10T16:05:30",
"date_gmt": "2020-12-10T16:05:30",
"guid": {},
"modified": "2020-12-10T16:05:31",
"modified_gmt": "2020-12-10T16:05:31",
"slug": "test",
"status": "publish",
"type": "place",
"link": "http://localhost:81/test/",
"title": {},
"content": {},
"featured_media": 0,
"template": "",
"acf": {
"address": {
"address": "123 Test Address",
"street_number": "123",
"street_name": "Test Address",
"city": "Philipsburg",
"state": "Sint Maarten",
"country": "Sint Maarten",
"country_short": "SX"
},
"header": {}
},
"_links": {}
},
etc
]
저는 그것을 Vuex에 저장하고 다음 방법으로 정보를 정리합니다.
computed: {
resorts() {
const resorts = {};
if (this.$store.state.loading === false) {
this.$store.state.posts.forEach((post) => {
const c = post.acf.address.country;
const s = post.acf.address.state;
//const t = post.title;
resorts[c] = resorts[c] || {};
resorts[c][s] = resorts[c][s] || [];
resorts[c][s].push(post);
});
}
return resorts;
},
}
정보를 표시하다v-for다음과 같은 루프(퍼그):
section.united-states(v-for="(country, index) in resorts" v-if="index==='United States'")
h1(v-html="index")
section.state(v-for="(state, subIndex) in country" :key="subIndex" :class="subIndex.toLowerCase()")
h5(v-html="subIndex")
ul
li(v-for="post, resort) in state")
listing(:id="post.id" :slug="post.slug" :image="post.acf.header" :title="post.title.rendered" :city="post.acf.address.city" :street="post.acf.address.street_name_short")
그러면 정보가 올바르게 표시됩니다.하지만 국가 이름, 주 이름, 시 이름 순으로 알파벳 순으로 정리해야 합니다.정리하려고 노력했고lodash.orderBy, 그러나 목록을 정리할 수 없었습니다.Chrome의 Vue 검사기 탭에서 계산된 국가 및 주(도시가 아님)가 알파벳 순으로 표시됩니다.좋은 의견이라도 있나?
한 가지 해결책은 투고를 주소별로 그룹화하기 전에 정렬하는 것입니다.
및 를 사용하여 유틸리티(이름 지정)를 만듭니다.sortPosts())를 사용하여 투고를 다음 순서로 정렬합니다.country,state,city,그리고나서street_name필드:
const sortPosts = posts =>
posts.slice().sort((a,b) => {
const countryA = a.acf.address.country
const countryB = b.acf.address.country
const stateA = a.acf.address.state
const stateB = b.acf.address.state
const cityA = a.acf.address.city || '' // can be undefined in Google Maps API
const cityB = b.acf.address.city || '' // can be undefined in Google Maps API
const streetA = a.acf.address.street_name
const streetB = b.acf.address.street_name
return countryA.localeCompare(countryB) || stateA.localeCompare(stateB) || cityA.localeCompare(cityB) || streetA.localeCompare(streetB)
})
이 투고를 그룹화하려면 이미 가지고 있는 논리와 같은 논리로 합니다만, 로컬의 데이터 타입을 변경할 필요가 있습니다.resorts에서 가변하다.Object로.Map왜냐하면 반복이 항상 삽입 순서를 따르는 것은 아니기 때문에, 이것은 정렬을 중단시킬 것입니다.sortPosts():
export default {
computed: {
resorts() {
// BEFORE:
// const resorts = {};
const resorts = new Map();
if (this.$store.state.loading === false) {
sortPosts(this.$store.state.posts).forEach((post) => {
const c = post.acf.address.country;
const s = post.acf.address.state;
// BEFORE:
// resorts[c] = resorts[c] || {};
// resorts[c][s] = resorts[c][s] || [];
// resorts[c][s].push(post);
if (!resorts.has(c)) {
resorts.set(c, new Map());
}
const stateMap = resorts.get(c);
if (!stateMap.has(s)) {
stateMap.set(s, []);
}
stateMap.get(s).push(post);
});
}
return resorts
},
}
}
v2.6.12 현재v-for지원하지 않습니다.Maps, 따라서 를 사용하여 를 반복할 수 있도록 합니다.v-for:
<section v-for="[country, countryData] in Array.from(resorts)" :key="country">
<h1 v-html="country" />
<section class="state" v-for="[state, posts] in Array.from(countryData)" :key="state" :class="state.toLowerCase()">
<h5 v-html="state" />
<ul>
<li v-for="(post, resort) in posts" :key="post.id">
...
</li>
</ul>
</section>
</section>
언급URL : https://stackoverflow.com/questions/65238851/sort-computed-object-and-array-by-two-fields
반응형
'programing' 카테고리의 다른 글
| C에서는 구조물을 반환할지 또는 구조물에 포인터를 반환할지 어떻게 선택할 수 있습니까? (0) | 2022.08.08 |
|---|---|
| Vuex는 모든 제품 정보와 API 요청 쿼리를 저장합니다. (0) | 2022.08.08 |
| Vuejs 앱에서 하이차트 다시 그리기 (0) | 2022.08.08 |
| System.gc()를 호출하는 것이 잘못된 방법인 이유는 무엇입니까? (0) | 2022.08.08 |
| 예외와 오류의 차이 (0) | 2022.08.08 |