查找从数组vue.js购买的最多



我正在努力寻找哪些帖子的购买量最大。。。我已经试了一段时间了,这是我的最新草稿。我真的很想知道是否有一种聪明的方法可以通过Vue js做到这一点。我的大部分挣扎都来自于在阵列中的导航。

我的第一个想法是把(买的(不同的数字合并在一起,然后确定最大的一个,然后试图找到这个数字,但没有成功。

有人能帮我吗?

Vue.createApp({
data() {
return {
postsPopular: null,
sortMethod: 2,
posts: [
{
id: 1,
theme: 'Todos',
name: 'Arcoiris',
amount: '1',
bought: 0
},
{
id: 2,
theme:'Clubs', 
name: 'Club America', 
amount: '2',
bought: 10
},
{
id: 3, 
theme:'Clubs', 
name: 'Club Chivas', 
amount: '3',
bought: 0
},
{
id: 4, 
theme:'Regionales', 
name: 'Sabucan Pitahaya', 
amount: '4',
bought: 0
},
{
id: 5, 
theme:'Regionales', 
name: 'Sabucan', 
amount: '5',
bought: 0
},
{
id: 6, 
theme:'Frutas', 
name: 'Sandia', 
amount: '6',
bought: 0
},
{
id: 7, 
theme:'Regionales', 
name: 'Xtabay', 
amount: '7',
bought: 0
}
],
}
},
methods: {
themeActive() {
//console.log(this.sortMethod.id.length);
},
},
computed: {
postsActive() {
if (this.sortMethod == '1') 
{
return (this.posts.slice(-7));
} 
else if (this.sortMethod == '2') 
{
this.postsPopular = this.posts.filter((item) => {
[i] = item.bought;
console.log(i);
popArray = concat(i);
popArray.reduce(function(previousValue, currentValue, currentIndex, popArray) {
return newPreviousValue;
}, 0);
});
console.log(postsPopular);
} 
else if (this.sortMethod == '3') 
{

} 
else if (this.sortMethod == '4') 
{

} 
else if (this.sortMethod == '5') 
{

}
},
rows() {
}
}
}).mount('#page2')

这个问题不是关于vuejs的,而是关于vanila-js的。要按属性查找最大对象,只需按此属性将所有对象相互比较即可。

const posts=[{id:1,theme:"Todos",name:"Arcoiris",amount:"1",bought:0},{id:2,theme:"Clubs",name:"Club America",amount:"2",bought:10},{id:3,theme:"Clubs",name:"Club Chivas",amount:"3",bought:0},{id:4,theme:"Regionales",name:"Sabucan Pitahaya",amount:"4",bought:0},{id:5,theme:"Regionales",name:"Sabucan",amount:"5",bought:0},{id:6,theme:"Frutas",name:"Sandia",amount:"6",bought:0},{id:7,theme:"Regionales",name:"Xtabay",amount:"7",bought:0}];
const maxBought = posts.reduce((max, item) => 
(max.bought > item.bought ? max : item), posts[0] ?? undefined);
console.log(maxBought);
.as-console-wrapper { max-height: 100% !important; top: 0; }

您可以创建一个计算属性,返回列表中购买次数最多的对象。要获得购买量最大的对象,请使用jsArray.prototype.reduce((方法。

computed:{
mostBought(){
return this.posts.reduce((prev,current)=>prev.bought>current.bought?prev:current); 
}
}

这是vue游乐场的链接

最新更新