ES6中检查对象是否为空

5
我需要检查状态是否已批准,因此如果为空,我会对其进行检查。什么是最有效的方法?
 {
      "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;
  };
3个回答

10

你可以这样做

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


我认为你不需要三元运算符,因为它最终会返回布尔值。 - Adnan

1

Please try it:

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
}

1

如果您确定user.verified是基于JSON模式的对象

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接