搜索表单多个字段javascript



假设有一个对象数组,比如

[
{
"fname": "Anne",
"lname": "Walker",
"email": "jaynewashington@exposa.com",
},
{
"fname": "Peterson",
"lname": "Dalton",
"email": "petersondalton@exposa.com",
},
{
"fname": "Velazquez",
"lname": "Calderon",
"email": "velazquezcalderon@exposa.com",
},
{
"fname": "Norman",
"lname": "Reed",
"email": "normanreed@exposa.com",
}
]

我想创建一个搜索过滤器,只按fname和lname进行搜索。之前有一个这样的问题,但它搜索了的所有字段

如何创建React搜索过滤器来搜索多个对象键值

有人能帮我吗?

可以吗?

const json = [
{
"fname": "Anne",
"lname": "Walker",
"email": "jaynewashington@exposa.com",
},
{
"fname": "Peterson",
"lname": "Dalton",
"email": "petersondalton@exposa.com",
},
{
"fname": "Velazquez",
"lname": "Calderon",
"email": "velazquezcalderon@exposa.com",
},
{
"fname": "Norman",
"lname": "Reed",
"email": "normanreed@exposa.com",
}
];
function search(str) {
const keyword = str.toLowerCase();
return json.filter(x => x.fname.toLowerCase().includes(keyword) || x.lname.toLowerCase().includes(keyword));
}

你应该提出一个你尝试过的例子,并说"嘿,伙计们,我在这些数据上尝试过这个,但它不起作用。"然而,这是一个对象数组,所以你可以做的是:

const magicFunction = (name, lastName, array) => {
return array.filter((el) => el.fname === name && el.lname === lastName);
}

您可以使用lodash库。使用查找或筛选功能。查找-用于单个结果和筛选多个结果示例-

let _ = require('lodash');
let data = [
{
"fname": "Anne",
"lname": "Walker",
"email": "jaynewashington@exposa.com",
},
{
"fname": "Peterson",
"lname": "Dalton",
"email": "petersondalton@exposa.com",
},
{
"fname": "Velazquez",
"lname": "Calderon",
"email": "velazquezcalderon@exposa.com",
},
{
"fname": "Norman",
"lname": "Reed",
"email": "normanreed@exposa.com",
}
]
let result = _.find(data, { fname: 'Norman', lname: 'Reed'})

没有库的另一种选择

let res = data.find(o => o.fname == "Norman" && o.lname == "Reed")
console.log(res)

相关内容

  • 没有找到相关文章

最新更新