Home > database >  In n values, check if exactly one is defined
In n values, check if exactly one is defined

Time:09-01

I have an JS-Object (key-value pairs) and the values can be undefined. But i want the code to do something else if only one of the values are defined. What is the easiest and best (efficient) way to check that? (See snippet below to clarify)

let obj = {x:undefined, y:undefined, z:1337}
let otherobj = {x:undefined, y:undefined, z:undefined}
let anotherobj = {x:1,y:2,z:3}

if(foo(obj) && !foo(otherobj) && !foo(anotherobj)){
  alert("!!!");
}

function foo(x){
  return true; // ???
}

CodePudding user response:

But i want the code to do something else if only one of the values are defined

You can use filter to get only the values that are not 'undefined'.

THen use .length === 1 to check if it's exactly 1 value

let obj = {x:undefined, y:undefined, z:1337}
let otherobj = {x:undefined, y:undefined, z:undefined}
let anotherobj = {x:1,y:2,z:3}

console.log('Test 1', objHasOneValue(obj));           // true
console.log('Test 2', objHasOneValue(otherobj));      // false
console.log('Test 3', objHasOneValue(anotherobj));    // false

function objHasOneValue(x){
    return Object.values(x).filter(a => a !== undefined).length === 1;
}

  • Related