I want to use eval to calculate the following string with multiple varaibles I have all the variables stored in my object
let myVars = {
a : 10,
b : 20,
c : 30,
}
let str = "a+b+c+10"
// how to evaluate the string ...
I'm not sure if I understood your question, but I will try my best to answer.
The eval() method will automatically get the variables from the global context. If you want to get the result, just save the result from the eval() function.
// Object destructuring for easier readability
let { a, b, c } = {
a : 10,
b : 20,
c : 30,
}
let str = "a + b + c + 10";
const total = eval(str);
console.log(total); // Should be: 70
The code above will return the result from the mathematical operation.
However, you should never use eval(), as it can run any code arbitrarily.
You have to mention that a+b+c... are for the myVars object so you have different ways:
let myVars = {
a : 10,
b : 20,
c : 30,
}
let str = "myVars.a+myVars.b+myVars.c+10"
console.log(eval(str))
Although I don't suggest this way to you because here we can use that without eval so that will be easier.
Another way is to use Regex:
let myVars = {
a : 10,
b : 20,
c : 30,
}
let str = "a+b+c+10"
const arrayName="myVars"
str=str.replace(/([a-z]+)/gi,arrayName+".$1")
console.log(eval(str))
Here you add the object name behind the variables dynamically with Regex.
Or simply you can do what you want without eval (If you want):
let myVars = {
a : 10,
b : 20,
c : 30,
}
let sum=Object.values(myVars).reduce((partialSum, a) => partialSum + a, 0) + 10;
console.log(sum)