Javascript validation of multiple booleans

  • A+

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(Boolean).length === 1; console.log(oneTrue);

As @deceze commented

Should there be more properties in the object: [obj.a, obj.b, obj.c].filter(Boolean)...


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: