gpt4 book ai didi

javascript - vue.js中的.includes()和.filter()

转载 作者:行者123 更新时间:2023-12-03 06:45:18 25 4
gpt4 key购买 nike

因此,我正在尝试在vue内部创建一种过滤方法,它的规则之一是过滤其公司ID在过滤列表中的对象。
因此,基本上,用户可以选择多个公司,并且vue将创建一个列表,例如[1,5,2,6],然后将此列表解析为processFilter()方法,并且现在应该过滤产品数组,使其仅包含其company id在产品创建的列表中的产品Vue。
产品阵列示例:

[
{
'id': 1,
'name': 'Prod1',
'min_price': '1',
'max_price': '2',
'currency': 'EUR',
'image': '<Some_big_url>',
'company': '1',
'sub_category': '2',
'created': '<some_big_date>',
'views': '10000'
}
]
我的processFilter方法:
processFilter() {
const subCategory = this.filtersSub;
const company = this.filtersComp;
const sortBy = this.filtersSort;
this.filtered = this.products.filter(
this.data.includes(subCategory) && this.data.includes(company)
);
},
测试此函数方法后,它将在控制台中返回以下内容:
vue.runtime.esm.js:1888 TypeError: Cannot read property 'includes' of undefined
at a.processFilter (category.vue:227)
at submit (category.vue?c00e:1)
at ne (vue.runtime.esm.js:1854)
at HTMLFormElement.n (vue.runtime.esm.js:2179)
at HTMLFormElement.Ji.o._wrapper (vue.runtime.esm.js:6917)
有没有办法使这项工作有效,还是应该以其他方式进行?
在有人问是我 console.log() company and this.filtersComp之前,是的,它们不是 undefined并在其中包含值,如下图所示:
enter image description here

最佳答案

我不知道过滤器内部的逻辑如何工作,但是过滤器接受回调函数,并且您在此处仅传递了一个 bool(boolean) 值:

  this.filtered = this.products.filter(
this.data.includes(subCategory) && this.data.includes(company)
);
您可以像这样更改它:
  this.filtered = this.products.filter( product => {
//if you console log here, product will be printed as many times as the
//lenght of this.products applying the boolean
console.log(product)

//return this.data.includes(subCategory) && this.data.includes(company)
//this will alway return the same value (true or false)
//probably you want to use the product in your logic
return product.sub_category.includes(subCategory) && product.company.includes(company)
});
但这没有多大意义,因为 this.data.includes(subCategory) && this.data.includes(company)的结果在每次迭代中始终是相同的,从而导致是否过滤所有元素。
您很可能需要使用 product来实际过滤数组。

关于javascript - vue.js中的.includes()和.filter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62920847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com