如何在JS中过滤多个字符串?

时间:2018-10-20 19:40:28

标签: javascript filter ecmascript-6 include filtering

我希望能够过滤数组中的多个字符串(类型)。例如,我想过滤以下数据结构中的类型并输入水果。 我想要实现的是一个经过过滤的数据对象。

const data = [{type: "meat", food: "hamburger"}, {type:"fruit", food:"banana"}, {type:"fish", food: "red snapper"}, {type:"vegetables", food:"fungi"}]

let filter1 = 'meat'
let filter2 = 'fruit'

const filteredData = data.filter( post => post.type.includes(filter1, filter2) ? post:'');

// My expected result after filtering: [{type: "meat", food: "hamburger"}, {type:"fruit", food:"banana"}]

不幸的是,它返回4个结果,而不是上面期望的2个。

我知道如何在_underscore.js之类的库中处理此问题,但我想在现代EcmaScript中实现它。

1 个答案:

答案 0 :(得分:6)

创建一个首先要包含的type数组,然后然后可以在该数组上使用.includes测试。 (当前,您的post.type.includes(filter1, filter2)不起作用,因为includes仅接受一个参数)

const data = [{type: "meat", food: "hamburger"}, {type:"fruit", food:"banana"}, {type:"fish", food: "red snapper"}, {type:"vegetables", food:"fungi"}]

let filter1 = 'meat'
let filter2 = 'fruit'

const filters = [filter1, filter2];

const filteredData = data.filter(({ type }) => filters.includes(type));
console.log(filteredData);

您还可以使用Set来降低运行时的复杂性

const data = [{type: "meat", food: "hamburger"}, {type:"fruit", food:"banana"}, {type:"fish", food: "red snapper"}, {type:"vegetables", food:"fungi"}]

let filter1 = 'meat'
let filter2 = 'fruit'

const filters = new Set([filter1, filter2]);

const filteredData = data.filter(({ type }) => filters.has(type));
console.log(filteredData);