在ReactJS中实现搜索功能
我想在我的表中进行搜索。我正在实现以下逻辑:在ReactJS中实现搜索功能,reactjs,Reactjs,我想在我的表中进行搜索。我正在实现以下逻辑: this.props.searchFunc.forEach(function(item) { if (item.name.toLowerCase().indexOf(document.getElementById("name").value.toLowerCase().trim()) != -1 && ?? // here i want to map through `test
this.props.searchFunc.forEach(function(item) {
if (item.name.toLowerCase().indexOf(document.getElementById("name").value.toLowerCase().trim()) != -1 &&
??
// here i want to map through `test` array and check if the value is present in the array
})
其中在item.name
中有一个字符串。
在我放置??的第二个id中,我有一个数组,名为test
,值为[“abc”,“def”,“ghi”]
但是我不知道如何映射数组并检查字符串是否存在的条件。我知道数组映射函数:
item.test.map(function(item,id) {
if(item.toLowerCase().indexOf(document.getElementById("name2").value.toLowerCase().trim()) != -1)
})
但问题是如何同时检查这两个条件,因为只有当两个条件都满足时,搜索才会起作用。使用过滤器和&
筛选器将返回回调函数中满足条件的所有项。在你的情况下,你只有一个条件。您可以使用“and”操作符添加另一个条件:&&
。如果数组中的某个项同时满足这两个条件,则该项将被包括在内
item.test.filter(function(item, id) {
if (
item.toLowerCase().indexOf(document.getElementById("name").value.toLowerCase().trim()) != -1
&& //some other condition
) {
return item
}
})
编辑
根据您的问题,我假设您的searchFunc
看起来像这样:
const searchFunc = [
{ name: "ABC", test: ["def", "another value"] },
{ name: "ABC", test: ["ghi", "def"] },
{ name: "Not I List", test: ["also not in list"] },
{ name: "ABC", test: ["Does not meet second condition"] }
];
和您的测试数组:
const test = ["abc", "def", "ghi"];
似乎要筛选名称等于任何值的项。getElementById(“name”).value.toLowerCase().trim()
返回其项。test
数组包含document.getElementById(“name2”).value.toLowerCase().trim()中的值
因此,作为示例,让我们将这些值保存在分别返回值abc
和def
的变量中:
const value1 = document.getElementById("name").value.toLowerCase().trim()) // abc
const value2 = document.getElementById("name2").value.toLowerCase().trim()) // def
现在,我们可以筛选既有项的值。名称===value1
,又有项的值。test
数组包含值2
:
const filteredItems = searchFunc.filter(function(item) {
if (
item.name.toLocaleLowerCase() === value1 &&
item.test.indexOf(value2) !== -1
) {
return true;
}
});
以下是一个片段:
const test=[“abc”、“def”、“ghi”];
const value1=document.getElementById(“名称”).value.toLowerCase().trim()//abc
const value2=document.getElementById(“name2”).value.toLowerCase().trim()//def
常量searchFunc=[
{name:“ABC”,test:[“def”,“另一个值”]},
{名称:“ABC”,测试:[“ghi”,“def”]},
{name:“不在列表中”,test:[“也不在列表中”]},
{name:“ABC”,测试:[“不满足第二个条件”]}
];
常量filteredItems=searchFunc.filter(函数(项){
如果(
item.name.toLocaleLowerCase()==value1&&
item.test.indexOf(值2)!=-1
) {
返回true;
}
});
console.log(filteredItems)代码>
这两个条件是什么?当用户在两个不同的字段中输入值时,我想检查名为“name”的简单变量和名为“test”的数组中是否存在该值。如何在数组和简单变量之间应用和条件。我的第二个条件不在“test”数组中。它存在于名为“name”的不同变量中,该变量不是数组,但它只包含一个普通字符串。我知道如何分别检查这两个条件,但在一起测试这两个条件时会产生混淆。&&
运算符将根据第一个条件进行检查,如果计算结果为真,则将根据第二个条件进行检查。您只需要在&&
之后编写第二个条件的表达式。