在 ES6 中检查对象是否为空

Jos*_*eph 2 javascript ecmascript-6 ecmascript-2016

我需要检查状态是否被批准,所以我检查它是否为空。最有效的方法是什么?

回复

 {
      "id": 2,
      "email": "yeah@yahoo.com",
      "approved": {
        "approved_at": "2020"
      },
      "verified": {
        "verified_at": "2020"
      }
    }
Run Code Online (Sandbox Code Playgroud)

代码

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

Nar*_*han 6

你可以这样做

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"}));
Run Code Online (Sandbox Code Playgroud)

或者更简单您可以使用三元运算符

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"}));
Run Code Online (Sandbox Code Playgroud)