javascript - 如何使用多个文本字符串条件从数组中过滤出多个对象
问题描述
我正在尝试编写一个测试,并且我有一个看起来像这样的对象数组:
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';
});
}
但是后来我得到了返回所有对象的数组,没有任何东西被过滤掉。任何帮助都会受到极大的欢迎。提前谢谢了
解决方案
您将获得所有返回的值,因为'Product Three'
它是一个truthy
值
像这样使用逻辑与运算符:
if (environment === 'test') {
menuOfProducts = menuOfProducts.filter(function (option) {
return option.text !== 'Product Two' && option.text !== 'Product Three';
});
}
如果您有多个option.text
to filter
,您可以创建这些值的数组并使用includes
:
if (environment === 'test') {
menuOfProducts = menuOfProducts.filter(function(option) {
return !['Product Two', 'Product Three'].includes(option.text);
});
}
推荐阅读
- python-3.x - 美丽的汤还是硒?
- cmake - CMake 宏中的返回结束上层 CMake 文件执行?
- c# - 查找带引号的字符串并替换双引号之间的内容
- spring-boot - 任何人都可以帮助我使用 Spring Boot CLI 和 Groovy 更改服务器的端口号
- angular - 离子形式在保存时保持刷新
- arrays - 何时使用转置在 Julia 中绘制轮廓
- css - 将 CSS 动画应用于特定元素,而不是其子元素
- c# - 调用 POST 方法时出现内部服务器错误
- android - MP图表未在布局内显示:Android
- python - 尝试在某些 GIMP Python 插件代码上运行 Sphinx 时出错