首页 > 解决方案 > 如何在 vue 中比较 array.include(arrayData)

问题描述

我有两个数组数据

checked: [
'orange', 'apple', 'juice'
]

和第二

products: [
 '0': {
    title: 'this is product title',
    categories: [
     'apple', 'juice'
    ]
  }
]

我想用复选框过滤具有计算属性的数据

我试过这个

computed: {
   filterProducts(){
       return this.products.filter(product => this.checked.includes(product.categories));
   }
}

但它不工作我该怎么做

标签: javascriptarraysvue.jsvuejs2

解决方案


您正在尝试检查字符串数组是否包含数组(即使您的初始数组包含数组也不起作用)。不要使用.includes(),而是使用.every()onproduct.categories来检查此数组中的所有项目是否都包含在选中的范围内:

const checked = ['orange', 'apple', 'juice'];

const products = [
  {
    title: 'this is product title',
    categories: ['apple', 'juice']
  }
];

const computed = products.filter(product => product.categories.every(item => checked.includes(item) || !checked.length));

console.log(computed);


推荐阅读