I have an object with a format like this:
const obj = {
key1: 'key1',
key2: ''
}
I want to do specific actions based on whether the value of the keys (key1 and key2 above) are both present, both not present, or if one or the other key is present. I have the following code:
const getValues = (obj) => {
if (!obj.key1 && !obj.key2) {
//Do something when both keys aren't present
}
if (!obj.key1 && obj.key2) {
//Do something when ONLY key2 is present
}
if (obj.key1 && !obj.key2) {
//Do something when ONLY key1 is present
}
//Do something when both keys are present
}
const finalValue = getValues(obj)
Is there a way to simplify the above code without using multiple if else statements. I can’t use multiple variables in case statements so was wondering on alternatives.
5
Answers
There’s nothing wrong with
if/else
, but if you want someting different, you might useternary
operator.Also, there’s a difference between
key present
andkey has truthy value
.In the snippet below I assume
key present
means key defined in the Object.I know you said you don’t want multiple if/else. But You would actually want to use if/else if/else. This way the if sequence will stop and not keep processing each if statement separately like your code.
There isn’t a lot to do to simplify your use case, just correct it.
You could always nest conditions:
Another way might be to create a two-bit map and then run a
switch
statement on the bitmap.You can use
if
s withoutelse
sIf you change the order, you can do something like this:
Just for the fun of it:
I don’t really recommend to use this, but it’s short and even shorter when it comes to 3 choices or more:
code the choices in a binary number and make s switch: