5

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": "[email protected]",
      "approved": {
        "approved_at": "2020"
      },
      "verified": {
        "verified_at": "2020"
      }
    }

CODE

    const checkIfEmpty = (user) => {
    if (Object.entries(user.verified).length === 0) {
      return true;
    }
    return false;
  };
0

3 Answers 3

10

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"}));

Sign up to request clarification or add additional context in comments.

1 Comment

I think you don't need Ternary Operator there, It will reture boolean anyway.
1

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

const checkIfEmpty = (user) => {
    return !!(user && user.verified);
};

Comments

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.