在 ES6 中检查对象是否为空

Check if Object is Empty in ES6

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

回应

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

代码

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

你可以这样做

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

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

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

如果您确定 user.verified 是基于 JSON 架构的对象

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

请试一试:

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

并使用:

if(isEmpty(user)) {
    // user is empty
} else {
    // user is NOT empty
}