You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤出category含cat_id为1对象的results数组元素?

Solution to Filter Results by Category cat_id

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 your results array and keeps only those products where the callback returns true.
  • product.category.some(...) checks if at least one element in the product's category array matches the condition (cat_id === 1). If the category array is empty (like product 3 in your sample), some() will return false, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:14:31