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

标签 javascript arrays typescript

我有以下数组:

 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'}]

我有一个搜索字段,我需要在其中使用搜索值过滤数组并返回匹配的对象。对我来说,这里的问题是我不知道上面的数组中可能有哪些键和值对,键值对是动态生成的,另外我如何使用正则表达式搜索数组。它应该与我输入的每个字符匹配并返回数组中的匹配对象?结果应该是这样的:

搜索键: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; }

关于javascript - 从键和值是动态的数组中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51659294/

相关文章:

javascript - 如何调用包装在 jQuery 函数中的 JavaScript 方法

不同浏览器中的 Javascript 滚动条类和鼠标滚轮速度

Javascript 选项处理

sql - Postgres GROUP BY 数组列

javascript - 跑马灯标签开始位置

C 程序循环数组旋转因超时而终止

python - 如何检查 Numpy 数组是否是另一个更大数组的子数组

typescript - 如何使用 Typescript 3.2.2 进行命令行编译?

javascript - TypeScript XAML 框架

reactjs - 无法使用 Typescript 在 React 的 onClick 属性上分配函数