首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将查询过滤器应用于JavaScript对象数组

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

Stack Overflow用户
提问于 2019-09-09 10:28:26
回答 1查看 63关注 0票数 5
代码语言: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']},

]

我正在尝试过滤看起来像上面的对象数组。假设我同时查询titlecustomer,前者是一个字符串,后者是一个字符串数组。

我创建了一个名为filterData的函数,该函数采用如下所示的对象

代码语言:javascript
复制
let filter_info = {
    title: ['aa, cc'], customer: ['b']
}

我希望该函数过滤掉在title中具有aa和在customers中具有b的对象,期望输出为

代码语言:javascript
复制
output = [
    { title: 'aa-1', customers: ['a', 'b']},
    { title: 'cc-1', customers: ['b', 'e', 'f']},
]

因为这是满足查询的两个对象(title包括aa和cc,customers包括'b')

我试过了

代码语言:javascript
复制
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是一个数组,而不是一个字符串。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-09 10:35:02

你就快到了。您可以在filter方法中的customers数组上使用Array.some(),如下所示:

代码语言:javascript
复制
item.customers.some(value => value.toLowerCase().includes(customer_filter))

那么您的filter方法将如下所示:

代码语言:javascript
复制
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))
              )
        ) 
    )
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57847196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档