从键和值都是动态的数组中搜索字符串



我有以下数组:

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搜索数组。它应该与每个字符I类型匹配,并在数组中返回匹配的对象?结果应该是这样的:

搜索关键字: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'}]

如有任何建议,我们将不胜感激。感谢

如果需要搜索字符串的部分或独立于大小写的值,可以过滤数组并通过直接检查来检查值。

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; }

最新更新