我正在嘗試設定一個采用兩個搜索條件(名稱和/或標簽)的應用程式。我為按名稱搜索設定了動態搜索。但我無法進一步過濾到標簽名稱的搜索中。我如何著手設定 2 個值的動態搜索。在我的情況下,您應該能夠通過name && tagor justname或 just進行搜索tag。
const filteredResults = studentData.filter((student) => {
const name = student.firstName " " student.lastName;
return (
name.toLowerCase().includes(searchTerm.toLowerCase()) ||
student.tags.filter((tag) => {
return tag.toLowerCase().includes(tagTerm.toLowerCase());
})
);
});
這是 api 資料的一個條目如下所示:
{
city: "Fush?-Muhurr"
??
company: "Yadel"
??
email: "[email protected]"
??
firstName: "Ingaberg"
??
grades: [ "78", "100", "92", … ]
??
id: "1"
??
lastName: "Orton"
??
pic: "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg"
??
skill: "Oracle"
??
tags: [ "Tag1", "Tag2" ]
}
如果有人想看一下,我將在此處鏈接我的 githubo 存盤庫(這是一個非常小的專案):https : //github.com/EricPezzulo/HatchwaysFrontendAssessment
uj5u.com熱心網友回復:
你可以試試這個
const result = studentData.filter(({
firstName,
lastName,
tags
}) => new RegExp(searchTerm, 'gui').test(`${firstName} ${lastName} ${tags.join(' ')}`));
uj5u.com熱心網友回復:
正如評論中提到的,您正在嘗試過濾兩者或其中之一。
以下代碼應恢復您一直要求的內容
const studentsArray = [{
city: "Fush?-Muhurr",
company: "Yadel",
email: "[email protected]",
firstName: "Ingaberg",
grades: [ "78", "100", "92"],
id: "1",
lastName: "Orton",
pic: "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg",
skill: "Oracle",
tags: [ "Tag1", "Tag2" ],
},
{
city: "Fush?-Muhurr",
company: "Yadel",
email: "[email protected]",
firstName: "Ingaberg",
grades: [ "78", "100", "92"],
id: "1",
lastName: "Orton",
pic: "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg",
skill: "Oracle",
tags: [ "Tag3", "Tag4" ],
}]
const searchTerm = ''
const tagTerm = ''
const filteredResults = studentsArray.filter((student) => {
const name = student.firstName ' ' student.lastName;
const nameIncludesSearchTerm = name.toLowerCase().includes(searchTerm.toLowerCase())
const tagsIncludesTagTerm = student.tags.map(t=>t.toLowerCase()).includes(tagTerm.toLowerCase())
const includesNameAndTag = nameIncludesSearchTerm && tagsIncludesTagTerm
const includeNameOrTag = nameIncludesSearchTerm || tagsIncludesTagTerm
return includesNameAndTag || includeNameOrTag;
});
console.log({filteredResults})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377985.html
標籤:javascript 数组 反应 搜索
