4
I have an empty object:
obj = {}
I’m trying to check if there’s a key op1
in that object. If there is I want to add the key and any value, getting like this:
obj = { op1: 10 } // O valor 10 é hipotético.
Case the key op1
exists in the object obj
i want to add any value to the value already existing in this key. For example, if:
obj = { op1: 10 }
And I come with a value 15, would be:
obj = { op1: 25 }
So far so good. I have a code that does this check and sum using if...else
:
var valor = 15;
if(obj["op1"]){
obj["op1"] += valor;
}else{
obj["op1"] = valor;
}
If the key op1
already exist in the obj
, i just update the value, if it doesn’t exist, I create the key op1
with the value of the variable valor
.
My question is: is there any way to eliminate this if...else
using a ternary operator, since the only difference between the if
and the else
is the operator +=
? Or else I’d have some way to simplify that if...else
?
Great question, I went through exactly this situation a few days ago and ended up creating a code with
if...else
as you quote.– Daniel Mendes