[英]search a string from an array whose keys and values are dynamic
我有以下數組:
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'}]
任何建議,將不勝感激。 謝謝
如果需要查找字符串的一部分或大小寫無關的值,則可以過濾數組並通過直接檢查來檢查值。
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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.