2

I need to check whether the status is approved or not, so i check it if it is empty. Whats the most efficient way to do this?

RESPONSE

 {
      "id": 2,
      "email": "yeah@yahoo.com",
      "approved": {
        "approved_at": "2020"
      },
      "verified": {
        "verified_at": "2020"
      }
    }

CODE

    const checkIfEmpty = (user) => {
    if (Object.entries(user.verified).length === 0) {
      return true;
    }
    return false;
  };
Joseph
  • 4,309
  • 11
  • 37
  • 87

3 Answers3

3

You can do this way

const checkIfVerifiedExists = (user) => {
    if (user && user.verified && Object.keys(user.verified).length) {
        return true;
    }
    return false;
};

console.log(checkIfVerifiedExists(null));
console.log(checkIfVerifiedExists({something: "a"}));
console.log(checkIfVerifiedExists({verified: null}));
console.log(checkIfVerifiedExists({verified: ""}));
console.log(checkIfVerifiedExists({verified: "a"}));
console.log(checkIfVerifiedExists({verified: "a", something: "b"}));

Or More simple You can use Ternary Operator

const checkIfVerifiedExists = (user) => {
    return (user && user.verified && Object.keys(user.verified).length) ? true : false
};

console.log(checkIfVerifiedExists(null));
console.log(checkIfVerifiedExists({something: "a"}));
console.log(checkIfVerifiedExists({verified: null}));
console.log(checkIfVerifiedExists({verified: ""}));
console.log(checkIfVerifiedExists({verified: "a"}));
console.log(checkIfVerifiedExists({verified: "a", something: "b"}));
sqram
  • 6,509
  • 8
  • 44
  • 61
Narendra Chouhan
  • 2,140
  • 1
  • 9
  • 17
1

if you are sure that user.verified is an object based on JSON schema

const checkIfEmpty = (user) => {
    return !!(user && user.verified);
};
D. Seah
  • 4,091
  • 1
  • 8
  • 18
1

Please try it:

const isEmpty = (obj) => {
    for(let key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

and use:

if(isEmpty(user)) {
    // user is empty
} else {
    // user is NOT empty
}
Thai Nguyen Hung
  • 1,040
  • 3
  • 10