如何过滤出category含cat_id为1对象的results数组元素?
Got it, let's get this sorted for you! The issue with your current code is that you're filtering the category array of each result and overwriting webCatProducts each time—so you end up with just the matching category objects (or an empty array for the last item) instead of keeping the full product objects that meet your condition.
Here's the correct approach using Array.filter() on the results array combined with Array.some() to check if the category array has at least one item with cat_id === 1:
this.webCatProducts = data.results.filter(product => { // Check if any category in the product's category array has cat_id 1 return product.category.some(categoryItem => categoryItem.cat_id === 1); }); console.log(this.webCatProducts);
How this works:
results.filter()iterates over every product in yourresultsarray and keeps only those products where the callback returnstrue.product.category.some(...)checks if at least one element in the product'scategoryarray matches the condition (cat_id === 1). If the category array is empty (like product 3 in your sample),some()will returnfalse, so that product gets excluded—exactly what you want.
Result with your sample data:
The webCatProducts array will only contain the first product object (product_id 1), since it's the only one with a category item where cat_id is 1.
Why your original code didn't work:
Your loop was replacing webCatProducts with the filtered category array of each individual product. For product 1, it would be the category object with cat_id 1; for product 2, an empty array; and for product 3, also an empty array. So by the end of the loop, webCatProducts would be empty instead of the list of products you need.
内容的提问来源于stack exchange,提问作者devmrh

