【问题标题】:How to check empty condition for an object如何检查对象的空状态
【发布时间】:2016-12-03 14:29:12
【问题描述】:

我有一个像下面这样的对象,但我不确定如何检查空状态 我的对象,

 "general_info" : {
    "parents_name" : "",
    "date_of_birth" : "",
    "second_day_attendance" : "",
    "class_day" : "",
    "reffered_by" : "",
    "year" : "",
    "amount_paid" : "",
    "next_due" : "",
    "payment_untill" : "",
    "payment_made" : ""
},

    if(general_info == ''){
      alert('empty')
    }

我知道我错了谁能帮帮我。谢谢。

【问题讨论】:

  • 您要检查所有属性是否为空?

标签: javascript angularjs object


【解决方案1】:

如果最终目的是检查所有属性值是否都是空字符串:

// retrieve an Array of the keys of the named Object:
Object.keys(general_info)
  // iterate over all the keys in the Array, using
  // Array.prototype.every() to see if all keys
  // match the supplied assessment:
  .every(
    // using an Arrow function to see if the current
    // property-value of the named key of the Object
    // is equal to a zero-length String:
    key => general_info[key] === ''
  );

【讨论】:

    【解决方案2】:

    使用Object#keys检查长度

    Object.keys(general_info).length
    // 10
    

    var general_info = {
        "parents_name" : "",
        "date_of_birth" : "",
        "second_day_attendance" : "",
        "class_day" : "",
        "reffered_by" : "",
        "year" : "",
        "amount_paid" : "",
        "next_due" : "",
        "payment_untill" : "",
        "payment_made" : ""
    };
    
    if(Object.keys(general_info).length > 0){
       console.log('Object is not empty');
    }

    【讨论】:

      【解决方案3】:

      您可以使用以下方法检查对象上是否存在属性。

      !Object.keys(obj).length
      

      const general_info = {
        "parents_name": "",
        "payment_made": ""
      }
      
      const empty_object = {}
      
      function isEmpty(obj) {
        return !Object.keys(obj).length
      }
      
      console.log(
        isEmpty(general_info)
      )
      console.log(
        isEmpty(empty_object) 
      )

      【讨论】:

        猜你喜欢
        • 2023-03-03
        • 1970-01-01
        • 2021-12-28
        • 2011-10-25
        • 1970-01-01
        • 2018-12-21
        • 2017-05-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多