在 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;
  };

原文由 Joseph 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 355
2 个回答

你可以这样做

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

原文由 Narendra Chouhan 发布,翻译遵循 CC BY-SA 4.0 许可协议

请尝试一下:

 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
}

原文由 Thai Nguyen Hung 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏