Search code examples
javascripttypescriptobject

How to check if an object has Truthy or falsely values using the double bang operator?


I am trying to check if an object has truthy or falsely values. If an object for example has all the truthy values then i want to do something. If the object values are not truthy i.e. are falsely e.g. 0, '' and undefined I want to do something else. However, it does not work like that it always exceute the first part of the if statement. Is there anything I am doing wrong ?

 class Truthy {
  a: string;
  b: number;
  c: object;

  constructor() {
    this.a = 'a';
    this.b = 1;
    this.c = {};
  }
}

 class Falsely {
  a: string;
  b: number;
  c: object;

  constructor() {
    this.a = '';
    this.b = 0;
    this.c = undefined;
  }
}

  const truthy = new Truthy()
  const falsely = new Falsely()

  if (!!truthy) {
    // do something 
  } else {
    // do something else 
  }

  if (!!falsely) {
    // do something 
  } else {
    // do something else 
  }

Solution

  • You need to create a function that tests if each property is truthy, then combine the results one at a time.

    1. Pass in the object as a param (or reference 'this' if it is a class method)
    2. Get all of the keys
    3. intialize boolean
    4. loop through and test each one
    5. return result

    This is a boolean function so you can place it into the if() that you want

    function istruthyObject(obj){
        const keys = Object.keys(obj);
        let allTruthy = true;
    
        for(let k=0; k<keys.length;k++){
            console.log(`val: ${obj[keys[k]]} boolean: ${!!obj[keys[k]]}`);
            allTruthy = allTruthy && !!obj[keys[k]];
        }
    
        return allTruthy;
    
    }
    
    let testYes = {
        a:"hello",
        b:5,
        c: true
    }
    
    let testNo = {
        a: "hello",
        b: 5,
        c: undefined
    }
    
    console.log(`returns true: ${istruthyObject(testYes)}`);
    console.log(`returns false: ${istruthyObject(testNo)}`);