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 AND 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
是一个数组,而不是一个字符串。
如果我想完成这个任务,正确的用法是什么?
最佳答案
你快到了。您可以使用 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))
)
)
)
关于javascript - 将查询过滤器应用于对象的 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57847196/