我正在嘗試對物件進行排序,因此它不必執行相同的回圈 n 次。
給定以下物件
movies = [
{
title: "The Lord of the Rings: The Fellowship of the Ring"
year: 2001
},
{
title: "The Lord of the Rings: The Two Towers"
year: 2002
},
{
title: "The Lord of the Rings: The Return of the King"
year: 2003
},
{
title: "A Beautiful Mind"
year: 2001
},
]
我希望電影按年份排序并出現在螢屏上:
Year 2003
- The Lord of the Rings: The Return of the King
Year 2002
- The Lord of the Rings: The Two Towers
Year 2001
- A Beautiful Mind
- The Lord of the Rings: The Fellowship of the Ring
為此,vue我可以做一些事情,比如定義一個物件years = [2003, 2002, 2001],然后
<div v-for="y in years">
{{ y }}
<div v-for="m in movies">
<div v-if="m.year == y">
{{ m.title }}
</div>
</div>
</div>
但是,我以這種方式重復陣列v-for的movies長度years。
所以我考慮movies用以下方式組織物件:
moviesByYear = [
2003: [
{
title: "The Lord of the Rings: The Return of the King"
year: 2003
}
],
2002: [
{
title: "The Lord of the Rings: The Two Towers"
year: 2002
}
],
2001: [
{
title: "A Beautiful Mind"
year: 2001
},
{
title: "The Lord of the Rings: The Fellowship of the Ring"
year: 2001
}
]
]
這樣我就可以使用
<div v-for="(movies, year) in moviesByYear" :key="year">
<div>{{ year }}</div>
<div v-for="m in movies">
{{ m.title }}
</div>
</div>
不幸的是,我無法構建moviesByYear陣列并且我不確定這是正確的方法,因為按鍵排序物件存在缺點。事實上,我需要按升序和降序對電影進行排序。
我該如何解決這個問題?有比運行v-forn 次更好的方法嗎?
uj5u.com熱心網友回復:
我可能會誤解,但首先您需要創建一個包含 year => 電影關系的物件陣列。您可以簡單地通過反轉陣列來創建反向排序(升序)。這樣你就可以使用一個簡單的可迭代 v-for,比如
<div v-for="year in movieList" >
<div>{{ year.year }}</div>
<div v-for="m in year.movies">
{{ m }}
</div>
</div>
let movies = [{
title: "The Lord of the Rings: The Fellowship of the Ring",
year: 2009
},
{
title: "The Lord of the Rings: The Two Towers",
year: 2002
},
{
title: "The Lord of the Rings: The Return of the King",
year: 2003
},
{
title: "A Beautiful Mind",
year: 2009
},
]
let movieList = movies.reduce((b, a) => {
let index = b.findIndex(f => f.year === a.year);
if (index < 0) b.push({
year: a.year,
movies: [a.title]
});
else b[index].movies.push(a.title);
return b;
}, []).sort((a, b) => b.year - a.year);
console.log(movieList)
console.log('reversed: ', movieList.reverse())
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432660.html
標籤:javascript 数组 Vue.js 排序 目的
