我有以下数组:
var Array = [{id:100,name:'N1',state:'delhi',country:'india',status:'active'},
{id:101,name:'N2',state:'kenya',country:'africa',status:'suspended'}
{id:102,name:'N3',state:'kerala',country:'india',status:'inactive'}
{id:103,name:'N4',state:'victoria',country:'australia',status:'active'}]
,我有一个搜索字段,在这里我需要用搜索到的值过滤数组并返回匹配的对象。对我来说,这里的问题是我不知道上面的数组中可能会包含哪些键和值对,键值对是动态生成的,另外我该如何使用Regex搜索数组。它应该与我输入的每个字符匹配,并在数组中返回匹配的对象吗?结果应如下所示:
搜索键:ind
[{id:100,name:'N1',state:'delhi',country:'india',status:'active'},
{id:102,name:'N3',state:'kerala',country:'india',status:'inactive'}]
搜索键:N2
[{id:101,name:'N2',state:'kenya',country:'africa',status:'suspended'}]
任何建议将不胜感激。谢谢
答案 0 :(得分:2)
如果需要查找字符串的一部分或不区分大小写的值,则可以过滤数组并通过直接检查来检查值。
function search(value) {
return array.filter(o => Object.values(o).some(v => v === value));
}
var array = [{ id: 100, name: 'N1', state: 'delhi', country: 'india', status: 'active' }, { id: 101, name: 'N2', state: 'kenya', country: 'africa', status: 'suspended' }, { id: 102, name: 'N3', state: 'kerala', country: 'india', status: 'inactive' }, { id: 103, name: 'N4', state: 'victoria', country: 'australia', status: 'active' }];
console.log(search('india'));
console.log(search('N2'));
.as-console-wrapper { max-height: 100% !important; top: 0; }