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

279
Visualizações
Creating a variable for each key value pair in JS

I have a problem...

I have a string that inputted by the user and looks something like this

let conditions = "id === 101 || name === 'Albert' && age !== 43"

I also have an array of data that was also created by the user at some point previously The data was stored in the form of an array that looks like so, and the user now has requested all data entries that match the conditions he has given.

let data = [
    {id:101, name:"Albert", age:63},
    {id:102, name:"Einstein", age:53}
]

You can probably see where I'm going with this. The array to be returned should look like this.

let returnedArray = [
    {id:101, name:"Albert", age:63}
]

Now, my first thought was just to use eval. Creating the variables with eval and for loop, checking with eval and so on.

But that would be very slow and seems redundant. Also, we can no longer declare variables with eval, and creating so many global variables would be quite harmful to my project.

Neither the conditions or the data array are static. The conditions are user inputed and the data arrays are not only ever changing, they are also user created.

Any suggestions?

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

0

Using eval would be the simplest way, there is no need to create a ton of global variables. We can use filter, and destructure each object into its properties which happen to match the condition's logic.

let conditions = "id === 001 || name === 'Albert' && age !== 43"

let data = [
    {id:001, name:"Albert", age:63},
    {id:002, name:"Einstein", age:53}
]

let output = data.filter(({id, name, age}) => eval(conditions));

console.log(output);

Another possibility is to change the structure of conditions so it's code instead of strings, removing the dangers of using eval:

let conditions = ({id, name, age}) => {
  return id === 001 || name === 'Albert' && age !== 43;
};

let data = [
    {id:001, name:"Albert", age:63},
    {id:002, name:"Einstein", age:53}
]

let output = data.filter(conditions);

console.log(output);

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