Home > Mobile >  ignore a object property while filtering is empty
ignore a object property while filtering is empty

Time:10-14

I am trying to filter object array based on user selected value from drop down list

As you see in below example I want to filter the array based on chain and officeid. If one of them is empty then I want to skip that filter.

let list = [{
      "index": 4,
      "chain": "aaa",
      "officeId": "bbb"
    },
    {
      "index": 5,
      "chain": "ccc",
      "officeId": "ddd"
      
    }];

function search(chain, office) {
 let data = list.filter(function(result) {
      return result.chain === chain && result.officeId === office;
 });
 
 console.log(data);
}

search('aaa','bbb');  // this will work fine
search('aaa',''); // this returns empty array
search('', 'bbb'); // empty array

In above 3 statements I am expecting same output for all

If both are empty then it should skip the filter and return original array

i.e search('', ''); should not apply any filters

CodePudding user response:

try using this instead, you just have to add one more condition

let list = [{
      "index": 4,
      "chain": "aaa",
      "officeId": "bbb"
    },
    {
      "index": 5,
      "chain": "ccc",
      "officeId": "ddd"
      
    }];

function search(chain, office) {
 let data = list.filter(function(result) {
      if( result.chain === chain && result.officeId === office){
         return result
      }
      if(!chain  && !office){
         return result;
      }
 });
 
 console.log(data);
}

search('aaa','bbb');  // this will work fine
search('aaa',''); // this returns empty array
search('', 'bbb'); // empty array
search("","");

You can also use a short hand like this

 let data = list.filter(function(result) {
      return (!chain && !office) || (result.chain === chain && result.officeId === office);
 });

CodePudding user response:

Just add null/empty checks for both the filters. You can use the condition (!chain || result.chain === chain) && (!office || result.officeId === office) so if the chain/office is not null or empty then only check for equality:

let list = [{
      "index": 4,
      "chain": "aaa",
      "officeId": "bbb"
    },
    {
      "index": 5,
      "chain": "ccc",
      "officeId": "ddd"
      
    }];

function search(chain, office) {
 let data = list.filter(function(result) {
      return (!chain || result.chain === chain) &&
             (!office || result.officeId === office);
 });
 
 console.log(data);
}

search('aaa','bbb');  
search('aaa',''); 
search('', 'bbb');
search('', '');

  • Related