2

I have the following array :

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

and I have a search field , where I need to filter the array with that searched value and return the matched object. The problem here for me is I donot know what key and value pairs may come in the above array , Key value pairs are generated dynamically ,also how can I search the array using Regex . It should match with each char I type and return the matching object in an array ? the result should look something like this :

search key : ind

[{id:100,name:'N1',state:'delhi',country:'india',status:'active'},
 {id:102,name:'N3',state:'kerala',country:'india',status:'inactive'}]

search key : N2

[{id:101,name:'N2',state:'kenya',country:'africa',status:'suspended'}]

Any suggestions would be appreciated. Thanks

1
  • bigArray.filter(obj => Object.values(obj).indexOf(searchTerm) > -1); - more elaborate code will be needed for partial matches. Commented Aug 2, 2018 at 17:35

1 Answer 1

3

You could filter the array and check the value by a direct check, if you need to seach for parts of strings or for case independent values.

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

Sign up to request clarification or add additional context in comments.

1 Comment

How can I filter using Regex , for each char

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.