Reputation: 61
I have some struggles calculating inside a for each function with JavaScript. I have one array of objects that looks like this:
[
{
"attribute_operator": "*",
"attribute_value_price": 3
},
{
"attribute_operator": "+",
"attribute_value_price": 2
},
{
"attribute_operator": "*",
"attribute_value_price": 2
}
]
As you see, every value has operator, and there is a starting price, so the real calculation should look like (if starting price is 6 for example):
6 * 3 + 2 * 2
So the output should be in that case 40.
I know how to do it for sum, but how to implement my operator easily?
tried like:
let total = starting_price.value
calculate_objects.forEach((a: { attribute_value_price: number; }) => {
total += a.attribute_value_price;
});
console.log(total);
Upvotes: 0
Views: 115
Reputation: 1
You can use string literal with eval function. eval function is useful when you want to calculate an expression.
const obj = [
{
"attribute_operator": "*",
"attribute_value_price": 3
},
{
"attribute_operator": "+",
"attribute_value_price": 2
},
{
"attribute_operator": "*",
"attribute_value_price": 2
}
]
let starting_price = 6;
let total = starting_price;
obj.forEach((a) => {
total =eval(`${total}${a.attribute_operator}${a.attribute_value_price}`) ;
});
console.log(total);
Warning: Executing JavaScript from a string is an BIG security risk.
With eval()
, malicious code can run inside your application without permission.
With eval()
, third-party code can see the scope of your application, whitch can lead to possible attacks.
Upvotes: -1
Reputation: 62676
This is a good case for reduce. The starting value is that starting_price
, and each turn of the loop applies a little function related to the operand...
const starting_price = 6;
const operations = [{
"attribute_operator": "*",
"attribute_value_price": 3
},
{
"attribute_operator": "+",
"attribute_value_price": 2
},
{
"attribute_operator": "*",
"attribute_value_price": 2
}
];
const operators = {
'*': (a, b) => a * b,
'+': (a, b) => a + b,
};
const result = operations.reduce((acc, el) => {
let operator = operators[el.attribute_operator];
let operand = el.attribute_value_price;
return operator(acc, operand);
}, starting_price);
console.log(result);
Upvotes: 3