Home > Blockchain >  Filter array in object with multiple condition
Filter array in object with multiple condition

Time:10-25

I'm doing a search feature that user will input there option in filter object, then they will get the list they want. So i have an array like this

let array = [
  {
    "id": 1,
    "form_items": [
      {
        "value_text": "test",
        "header_id": 1,
        "value_number" 2000
      },
      {
        "value_text": "test 2",
        "header_id": 2,
        "value_number" null
      }
    ]
  },
  {
    "id": 2,
    "form_items": [
      {
        "value_text": "test 3",
        "header_id": 3,
        "value_number": 1000
      }
    ]
  }
]

and i have an object for filter like this

let filter = {
    "value_text": "test 2",
    "value_number": 2000
}

how can i return my array base on my filter object that element in form_items array match the condition ex: "test 2" in "header_id" : 2 and 2000 in "header_id" : 1

So my result will looks like this

[
  {
    "id": 1,
    "form_items": [
      {
        "value_text": "test",
        "header_id": 1,
        "value_number" 2000
      },
      {
        "value_text": "test 2",
        "header_id": 2,
        "value_number" null
      }
    ]
  }
]

CodePudding user response:

You can do this with few loops, but It could be put into smaller functions.

var results = [];

for(const element of array){
    // 1. Find all formItems that are matching your filter for each element
    let matchingFormItems = []; // create an result array of formItems matching your filter criteria
    for(const formItem of array['form_items']){  // iterate over all form_items
       for(let filterKey: Object.keys(filter)){ // for each filter key, check if current formItem matches filter criteria
         if(filter[filterKey] === formItem[filterKey]){ // if filter key is matching property from the formItem, push it to result Array
            matchingFormItems.push(formItem);
            break;// if one filter is matching, you can skip other
         }
      }

    }

  // 2. If at least one formItem has been found - push new object to the result array
  if(matchingFormItems.length > 0 ){
     results.push({ // it's best not to mutate input array, so we need to clone the object with only desired formItems.
         'id': element.id,
         'form_items': matchingFormItems
     });
 }
}
  • Related