Filter array of objects whose any properties contains a value

后端 未结 8 1087
你的背包
你的背包 2020-12-13 19:26

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

相关标签:
8条回答
  • 2020-12-13 19:59

    function filterByValue(arrayOfObject,words){
      let reg = new RegExp(words,'i');
      return arrayOfObject.filter((item)=>{
         let flag = false;
         for(prop in item){
           if(reg.test(prop)){
              flag = true;
           }  
         }
         return flag;
      });
    }

    0 讨论(0)
  • 2020-12-13 20:01

    Here's how I would do it using lodash:

    const filterByValue = (coll, value) =>
      _.filter(coll, _.flow(
        _.values,
        _.partialRight(_.some, _.method('match', new RegExp(value, 'i')))
      ));
    
    filterByValue(arrayOfObject, 'lea');
    filterByValue(arrayOfObject, 'ita');
    
    0 讨论(0)
提交回复
热议问题