如何检查对象的空状态

时间:2016-12-03 14:29:12

标签: javascript angularjs object

我有一个像下面的对象,但我不知道如何检查空状态 我的目标,

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

我知道我错了,任何人都可以帮助我。谢谢。

2 个答案:

答案 0 :(得分:1)

使用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');
}




答案 1 :(得分:-1)

您可以使用以下内容检查对象的属性是否存在。

!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) 
)