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

标签 javascript

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 中有 aacustomers 中有 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/

相关文章:

javascript - jQuery Mobile -> 覆盖 jQuery UI Datepicker -> 布局损坏

javascript - 为什么我的 jQuery.post() ajax 在我返回一个 View 时失败,但在我返回另一个 View 时却没有失败?

javascript - 结合传说中的系列

javascript - 在 GA 跟踪流程中应将用户 ID 放在哪里?

javascript - Firefox 删除持久性 Cookie

javascript - AngularJS 在 ng-change 调用的函数中将属性值作为参数传递

javascript - React 使用方法参数作为对象键来更新状态

javascript - Jquery 使新插入的 div 可拖动

javascript - 如何使用 lodash 获取对象的前 n 个元素?

javascript - 谷歌分析多域版本 5 JS 语法