Filter array of objects whose properties contains a value in JavaScript


Suppose, we have an array of objects like this −

const arr = [{
   name: 'Paul',
   country: 'Canada',
}, {
   name: 'Lea',
   country: 'Italy',
}, {
   name: 'John',
   country: 'Italy',
}, ];

We are required to devise a way to filter an array of objects depending on a string keyword. The search has to be made in any properties of the object.

For instance −

When we type "lea", we want to go through all the objects and all their properties to return the objects that contain "lea".
When we type "italy", we want to go through all the objects and all their properties to return the objects that contain italy.

Example

The code for this will be −

const arr = [{
      name: 'Paul',
      country: 'Canada',
   }, {
      name: 'Lea',
      country: 'Italy',
   }, {
      name: 'John',
      country: 'Italy',
}, ];
const filterByValue = (arr = [], query = '') => {
   const reg = new RegExp(query,'i');
   return arr.filter((item)=>{
      let flag = false;
      for(prop in item){
         if(reg.test(item[prop])){
            flag = true;
         }
      };
      return flag;
   });
};
console.log(filterByValue(arr, 'ita'));

Output

And the output in the console will be −

[
   { name: 'Lea', country: 'Italy' },
   { name: 'John', country: 'Italy' }
]

Updated on: 20-Nov-2020

782 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements