【问题标题】:How to filter multiple field conditionally in Javascript如何在Javascript中有条件地过滤多个字段
【发布时间】:2021-03-29 17:58:15
【问题描述】:

如何在 Javascript 中按条件过滤多个字段。

嗨,我想使用过滤器过滤 javascript 中的一些数据,但在这种情况下,我想接受值,基本上我想要做的是我想创建一些搜索输入然后返回数据,但我也希望当用户在搜索输入中输入category 时,结果也显示类别

const items = [
    { name: "Magazine", category: "Book"},
    { name: "Marker", category: "Pen"},
    { name: "Litelature", category: "Book"},
    { name: "Comics", category: "Book"},
    { name: "Drawer", category: "Pen"}
]

这里我已经实现了搜索过滤器。

const input = "Pen"
const filtered = items.filter((item) =>
    item.name.toLowerCase().includes(input.toLowerCase())
)

您可以看到代码没有返回任何内容,因为只过滤了名称字段。我如何对类别字段也实施过滤器

【问题讨论】:

  • 你的意思是filter(a => a.f1==x && a.f2==y)

标签: javascript arrays filter


【解决方案1】:

使用or 条件,例如

const input = "Pen"
const filtered = items.filter((item) =>
    item.name.toLowerCase().includes(input.toLowerCase()) ||
    item.category.toLowerCase().includes(input.toLowerCase())
)

【讨论】:

    猜你喜欢
    • 2014-01-28
    • 2020-04-23
    • 1970-01-01
    • 2016-08-04
    • 2021-11-20
    • 2017-01-23
    • 2020-08-05
    • 2015-10-28
    相关资源
    最近更新 更多