Filter array of objects whose any properties conta

2020-02-23 08:09发布

I'm wondering what is the cleanest way, better way to filter an array of objects depending on a string keyword. The search has to be made in any properties of the object.

When I type lea I want to go trough all the objects and all their properties to return the objects that contain lea

When I type italy I want to go trough all the objects and all their properties to return the objects that contain italy.

I know there are lot of solutions but so far I just saw some for which you need to specify the property you want to match.

ES6 and lodash are welcome !

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

    filterByValue(arrayOfObject, 'lea')   // => [{name: 'Lea',country: 'Italy'}]
    filterByValue(arrayOfObject, 'ita')   // => [{name: 'Lea',country: 'Italy'}, {name: 'John',country: 'Italy'}]

8条回答
forever°为你锁心
2楼-- · 2020-02-23 08:43

Use Object.keys to loop through the properties of the object. Use reduce and filter to make the code more efficient:

 const results = arrayOfObject.filter((obj)=>{
     return Object.keys(obj).reduce((acc, curr)=>{
           return acc || obj[curr].toLowerCase().includes(term);
     }, false);
}); 

Where term is your search term.

查看更多
Deceive 欺骗
3楼-- · 2020-02-23 08:46

You can always use array.filter() and then loop through each object and if any of the values match the value you are looking for, return that object.

const arrayOfObject = [{
      name: 'Paul',
      country: 'Canada',
    }, {
      name: 'Lea',
      country: 'Italy',
    }, {
      name: 'John',
      country: 'Italy',
    }, ];
    
let lea = arrayOfObject.filter(function(obj){
  //loop through each object
  for(key in obj){
    //check if object value contains value you are looking for
    if(obj[key].includes('Lea')){
      //add this object to the filtered array
      return obj;
      }
     }
    });
      
console.log(lea);

查看更多
登录 后发表回答