开发人员大家好,我现在正在开发这个应用程序,正在使用下拉列表过滤元素,查询 json 对象并将其与当时下拉列表中选定的元素进行比较。 但任何时候我只选择一个元素,它都不会显示任何结果。 这是我的 json 对象,它由名为“getAllProducts”的 getter 访问:
{
"user":null,
"products":[
{
"product_name":"Chain Saw",
"product_category":[
{
"categories_of_product":"Good"
},
{
"categories_of_product":"Danger"
},
{
"categories_of_product":"Homer"
}
]
},
{
"product_name":"Chuky",
"product_category":[
{
"categories_of_product":"Danger"
},
{
"categories_of_product":"Homer"
}
]
},
{
"product_name":"Glasses",
"product_category":[
{
"categories_of_product":"Good"
},
{
"categories_of_product":"Homer"
}
]
},
{
"product_name":"Tile",
"product_category":[
{
"categories_of_product":"Horror"
},
{
"categories_of_product":"Homer"
}
]
},
{
"product_name":"Mouse",
"product_category":[
{
"categories_of_product":"Homer"
}
]
},
{
"product_name":"rino",
"product_category":[
{
"categories_of_product":"Zoo"
},
{
"categories_of_product":"Park"
}
]
},
{
"product_name":"Chain Saw",
"product_category":[
{
"categories_of_product":"Homer"
},
{
"categories_of_product":"Horror"
}
]
},
{
"product_name":"Chain Saw1",
"product_category":[
{
"categories_of_product":"Homer"
},
{
"categories_of_product":"Good"
}
]
},
{
"product_name":"Chain Saw2",
"product_category":[
{
"categories_of_product":"Good"
}
]
},
{
"product_name":"rino1",
"product_category":[
{
"categories_of_product":"Zoo"
},
{
"categories_of_product":"Animal"
}
]
}
]
}
然后在我的方法中,我声明了一个函数,该函数先前针对一个 v 建模的全局变量,该变量遵循我的 html 中的某个标记,该标记是从应用程序组件之一导入的(所有这些都完美运行)。可以说:
SCRIPT
data(){
return{
CategoriesDropDown: "",
}
},
methods:{
filterSearch(selectedCategory) {
this.CategoriesDropDown = selectedCategory;
},
}
然后在我的最后一步,当我尝试用 this.CategoriesDropDown 过滤所有元素时,它不起作用,只需选择我的 dropDown 的任何类别,我的所有产品就会消失。这里我设置了访问与下拉列表中所选选项进行比较的 json 对象应该进行过滤,但不起作用:
COMPUTED
callProducts() {
if (this.CategoriesDropDown) {
return this.getAllProducts.products.forEach(categories => {
return categories.product_category.filter(string => {
return string.categories_of_product.toUpperCase() === this.CategoriesDropDown.toUpperCase()
;
});
});
} else {
return this.getAllProducts.products;
}
},
关于如何改进最后一个功能以正确过滤我的产品有什么建议吗?提前致谢!!!
最佳答案
将 this.getAllProducts.products.forEach(...)
中的 forEach
替换为 filter
。
像这样:
return this.getAllProducts.products.filter(categories => { // return only some products
return categories.product_category.filter(string => {
return string.categories_of_product.toUpperCase() === this.CategoriesDropDown.toUpperCase()
}).length !== 0 // check that product has selected category
});
关于javascript - 在使用 forEach 然后过滤查询后,通过 JavaScript 中的下拉列表进行过滤不会抛出任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61142780/