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']
}
我希望函数过滤出aa
中有title
和b
中有customers
的对象,期望输出是
output = [
{ title: 'aa-1', customers: ['a', 'b']},
{ title: 'cc-1', customers: ['b', 'e', 'f']},
]
因为这是满足查询条件的两个对象(标题包含aa和cc,客户包含'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
是一个数组,而不是字符串,这给了我一个错误。
如果我想完成此任务,正确的用法是什么?
答案 0 :(得分:7)
您快到了。您可以像这样在filter方法中对客户数组使用Array.some():
item.customers.some(value => value.toLowerCase().includes(customer_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))
)
)
)