Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

56
Views
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?

7 months ago · Juan Pablo Isaza
1 answers
Answer question

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);

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.