簡體   English   中英

如何在 Javascript 中有條件地過濾多個字段

[英]How to filter multiple field conditionally in Javascript

如何有條件地過濾 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())
)

正如您所看到的,該代碼沒有返回任何內容,因為只過濾了名稱字段。 我如何對類別字段也實施過濾器

使用or條件,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM