I want to validate an object that has three Boolean properties, of which one, and only one, must be true. What is the best way to check this?
I came up with this:
var t1 = obj.isFirst ? 1 : 0,
t2 = obj.isSecond ? 1 : 0,
t3 = obj.isThird ? 1 : 0;
var valid = (t1 + t2 + t3) === 1;
This works fine, but it feels a bit like a hobbyists solution :-)
Is there a better way of doing this? Using XOR (^) for example?
You could filter the Object.values and check if the length is 1
let obj = {
a: true,
b: false,
c: false
};
let oneTrue = Object.values(obj).filter(e => e === true).length === 1;
console.log(oneTrue);
As @deceze commented
Should there be more properties in the object:
[obj.a, obj.b, obj.c].filter(Boolean)...
Note that in your case, it might make sense to add a method to your object that does the check for you
let obj = {
a: false,
b: false,
c: false,
isValid() {
return this.a + this.b + this.c === 1;
}
};
console.log(obj.isValid());
You can use array.reduce:
var obj = {
a: true,
b: false,
c: false
};
var res = Object.values(obj).reduce((m, o) => m + o) === 1;
console.log(res);
Use:
obj.isFirst + obj.isSecond + obj.isThird === 1
Assuming it is certain that the values are Booleans and not something different. You can add explicit conversion if you like, like this:
Number(obj.isFirst) + Number(obj.isSecond) + Number(obj.isThird) === 1
But JavaScript also implicitly does this conversion for you.
(This is based on ASDFGerte’s comment.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With