【问题标题】:Check if Object is Empty in ES6 [duplicate]检查 ES6 中的对象是否为空 [重复]
【发布时间】:2020-10-05 14:26:59
【问题描述】:

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

回复

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

【问题讨论】:

    标签: javascript ecmascript-6 ecmascript-2016


    【解决方案1】:

    你可以这样做

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        请试一试:

        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
        }
        

        【讨论】:

          猜你喜欢
          • 2017-08-06
          • 2020-02-03
          • 2015-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-20
          • 2021-07-17
          相关资源
          最近更新 更多