【问题标题】:how to compare array.include(arrayData) in vue如何在 vue 中比较 array.include(arrayData)
【发布时间】:2019-09-29 08:04:45
【问题描述】:

我有两个数组数据

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));
   }
}

但它不工作我怎么能这样做

【问题讨论】:

    标签: javascript arrays vue.js vuejs2


    【解决方案1】:

    您可以为此使用.every()

    这是一个例子:

    checked = [
      'orange', 'apple', 'juice'
    ]
    
    products = [{
      title: 'this is product title',
      categories: [
        'apple', 'juice'
      ]
    }];
    
    const filteredProducts = products.filter(({ categories }) => categories.every(cat => checked.includes(cat)));
    
    console.log(filteredProducts);

    这将返回具有categories 数组的产品数组,其所有值都包含在checked 数组中。

    我不确定这是否正是您想要做的,如果您想使用categories 数组获取所有产品,该数组至少具有checked 数组中的一个值,使用.some() 而不是.every()

    【讨论】:

    • 我可以知道检查的数据是否为空,我还想如何显示所有产品吗?
    • @sidheart 如果checked 数组为空,您可以跳过过滤,例如const filteredProducts = !checked.length ? products : products.filter.....
    【解决方案2】:

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

    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);

    【讨论】:

    • 感谢它的工作,但我可以知道检查的数据是否为空,我还想如何显示所有产品?
    • @sidheart 您可以在.every() 谓词中添加|| !checked.length。我已经更新了答案
    猜你喜欢
    • 2014-11-04
    • 2011-05-11
    • 2018-10-12
    • 2016-09-16
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多