将查询过滤器应用于 JavaScript 对象数组

5
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']},

]

我将尝试筛选上述对象数组。 假设我提供了对titlecustomer的查询,它们分别是字符串和字符串数组。
我创建了一个名为filterData的函数,该函数接受一个对象,该对象如下所示。
let filter_info = {
    title: ['aa, cc'], customer: ['b']
}

我希望该函数过滤掉标题中含有aa,且客户名称中含有b的对象,期望输出结果为:
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是一个数组而不是字符串,因此这会给我带来错误。

如果我想完成这个任务,正确的用法是什么?

1个回答

7

您已经接近成功了。您可以在过滤方法中使用 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))
              )
        ) 
    )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接