首页 > 解决方案 > 如何使用多个文本字符串条件从数组中过滤出多个对象

问题描述

我正在尝试编写一个测试,并且我有一个看起来像这样的对象数组:

menuOfProducts: [ 
  { text: 'Product One',
    selector: '#product-one #productone',
    path: 'productone' },
  { text: 'Product Two',
    selector: '#product-two #producttwo',
    path: 'shop/catalog/producttwo' },
  { text: 'Product Three',
    selector: '#product-three #productthree',
    path: 'shop/catalog/productthree' },
  { text: 'Product Four',
    selector: '#product-four #productfour',
    path: 'shop/catalog/productfour' },
  { text: 'Product Five',
    selector: '#product-five #productfive',
    path: 'shop/catalog/productfive' }
]

我想做的是过滤掉几个对象并返回其余的。

到目前为止,我已经尝试使用 .filter() 过滤掉其中一个可以正常工作的对象。但是,可能需要按文本过滤出多个产品。这就是我现在所拥有的:

if (environment === 'test') {
  menuOfProducts = menuOfProducts.filter(function (option) {
    return option.text !== 'Product Two';
  });
}

并使用这个过滤器,我得到正确的数组返回减去“产品二”:

[ 
  { text: 'Product One',
    selector: '#product-one #productone',
    path: 'productone' },
  { text: 'Product Three',
    selector: '#product-three #productthree',
    path: 'shop/catalog/productthree' },
  { text: 'Product Four',
    selector: '#product-four #productfour',
    path: 'shop/catalog/productfour' },
  { text: 'Product Five',
    selector: '#product-five #productfive',
    path: 'shop/catalog/productfive' }
]

但如上所述,我现在想通过文本过滤多个对象。并且想知道我该如何解决这个问题?我尝试在过滤器中传递另一个条件,如下所示:

if (environment === 'test') {
  menuOfProducts = menuOfProducts.filter(function (option) {
    return option.text !== 'Product Two' || 'Product Three';
  });
}

但是后来我得到了返回所有对象的数组,没有任何东西被过滤掉。任何帮助都会受到极大的欢迎。提前谢谢了

标签: javascriptfilteringnightwatch.js

解决方案


您将获得所有返回的值,因为'Product Three'它是一个truthy

像这样使用逻辑与运算符:

if (environment === 'test') {
  menuOfProducts = menuOfProducts.filter(function (option) {
    return option.text !== 'Product Two' && option.text !== 'Product Three';
  });
}

如果您有多个option.textto filter,您可以创建这些值的数组并使用includes

if (environment === 'test') {
  menuOfProducts = menuOfProducts.filter(function(option) {
    return !['Product Two', 'Product Three'].includes(option.text);
  });
}

推荐阅读