samedi 25 septembre 2021

Dynamic if conditions in JavaScript

Is there anyways to pass the condition for if statement dynamically along with its operator without using eval() or new function() that affects it's performance.

<script>

var Students =  [{
            "name": "Raj",
             "Age":"15",
            "RollNumber": "123",
            "Marks": "99",
              
        }, {
            "name": "Aman",
             "Age":"14",
            "RollNumber": "223",
            "Marks": "69",
           },
           {
            "name": "Vivek",
             "Age":"13",
            "RollNumber": "253",
            "Marks": "89",
           }
        ];



*Number of condition are dynamic. can even contain 3 or 4 condition at a time*

var condition = [{"attribute":"el.Age","operator":">=","value":14},
                 {"attribute":"el.Marks","operator":"<=","value":70}];

var newArray =Students.filter(function (el)
{
  if( condition[0].attribute condition[0].operator condition[0].value && condition[1].attribute condition[1].operator condition[1].value ){
  
return true;
  
});

console.log(newArray);
</script>

Aucun commentaire:

Enregistrer un commentaire