Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In n values, check if exactly one is defined

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; // ???
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading