Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

374
Visualizações
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>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Yes, you pass the operands and the operator into a function that dispatches based on the operator to something that does the operation.

As a code sketch:

const operators = new Map([
    ["<", lt],
    [">", gt],
    ["<=", lte],
    [">=", gte],
    // ...
]);
function evaluate(operator, leftOperand, rightOperand) {
    const evaluator = operators.get(operator);
    if (!evaluator) {
        throw new Error(`Unknown operator ${operator}`);
    }
    return evaluator(leftOperand, rightOperand);
}

...where lt, gt, etc. are functions that perform the operation. I've used operator, leftOperand, and rightOperand above, but you could use attribute and value if you prefer. You'll need something like this to get the value of the "attribute" (the JavaScript term is "property").

(Or you could do the operations in the evaluate function itself in a big switch.)

Then you use that function in the filter:

let newArray = Students.filter(student => conditions.every(({operator, attribute, value}) => {
    const leftOperand = getProperty(student, attribute);
    return evaluate(operator, leftOperand, value);
}));

I've used every there because you're using an && condition. (Note I renamed the condition array to conditions since arrays hold more than one value.)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda