DEV Community

Md. Khalid Hossen
Md. Khalid Hossen

Posted on

how use dynamic condition is filtering in react js

Suppose you have an array of Json your task is need to filter the array dynamically with six different type of values. The values are store dynamically into json object.If object value change you need to push new conditions.

My Working procedure:

  1. declare an array where we push our conditions.
  2. If condition matches then push new condition into that array.
  3. then filter data and check each condition with every function
const [formdata, setFormdata] = useState({});

##handle onchange
setFormdata({ ...formdata, 
            [e.target.name]: e.target.value 
           });

let conditions = []
if (formdata.geography) {
    conditions.push(function (item) {
        return item.geography === formdata.geography;
      });
  };

if (formdata.traffic_type) {
    conditions.push(function (item) {
     return item.trafficType === formdata.traffic_type;
        });
  };

  if (formdata.task_type) {
      conditions.push(function (item) {
         return item.taskType === formdata.task_type;
     })
 };

 if (formdata.status_type) {
     conditions.push(function (item) {
         return item.statusType === formdata.status_type;
     })
}

 if (formdata.rev_type){
    conditions.push(function (item) {
        return item.revType === formdata.rev_type;
    })
}

if (formdata.device_type){
   conditions.push(function (item) {
       return item.deviceType === formdata.device_type;
   })
}

 const itemsMatchingCondition = campaigns.filter(d => 
                                conditions.every(c => c(d)));

console.log(itemsMatchingCondition);
Enter fullscreen mode Exit fullscreen mode

Note: If you have any issue feel free to knock me. I am happy to contribute with you.

Top comments (0)