const sample_table1_data = [
{ title: 'aa-1', customers: ['a', 'b']},
{ title: 'aa-2', customers: ['a', 'c']},
{ title: 'bb-1', customers: ['d', 'e']},
{ title: 'cc-1', customers: ['b', 'e', 'f']},
{ title: 'dd-1', customers: ['f', 'g']},
{ title: 'dd-2', customers: ['g']},
]我正在尝试过滤看起来像上面的对象数组。假设我同时查询title和customer,前者是一个字符串,后者是一个字符串数组。
我创建了一个名为filterData的函数,该函数采用如下所示的对象
let filter_info = {
title: ['aa, cc'], customer: ['b']
}我希望该函数过滤掉在title中具有aa和在customers中具有b的对象,期望输出为
output = [
{ title: 'aa-1', customers: ['a', 'b']},
{ title: 'cc-1', customers: ['b', 'e', 'f']},
]因为这是满足查询的两个对象(title包括aa和cc,customers包括'b')
我试过了
filterData = (filters) => {
let title_filter = filters.title
let customer_filter = filters.customer
const myItems = this.state.table1_data
const keywordsToFindLower = title_filter.map(s => s.toLowerCase());
const customerKeywords = customer_filter.map(s => s.toLowerCase())
// filters the profile data based on the input query (selected option)
const newArray = myItems.filter(item =>
keywordsToFindLower.some(
title_filter => (item.title.toLowerCase()).includes(title_filter)
)
&&
customerKeywords.some(
customer_filter => (item.customers.toLowerCase()).includes(customer_filter)
)
)
}但是,这给了我一个错误,因为customers是一个数组,而不是一个字符串。
如果我想完成这个任务,正确的用法是什么?
发布于 2019-09-09 10:35:02
你就快到了。您可以在filter方法中的customers数组上使用Array.some(),如下所示:
item.customers.some(value => value.toLowerCase().includes(customer_filter))那么您的filter方法将如下所示:
const newArray = myItems.filter(item =>
keywordsToFindLower.some(
title_filter => (item.title.toLowerCase()).includes(title_filter)
)
&&
customerKeywords.some(
customer_filter =>
(item.customers.some(
value => value.toLowerCase().includes(customer_filter))
)
)
)https://stackoverflow.com/questions/57847196
复制相似问题