Check if an object is empty? js

In fact, it is often encountered in the development process to determine whether objects and arrays are empty? Here are three ways to determine whether an object is empty

1. The most common idea, for...in... iterates over properties, if true, it is "non-empty array"; otherwise, it is "empty array"

function judgeObj(obj){
    for(var attr in obj){
          return  console.log('非空对象')
    }
    return console.log('empty object' )
}

 

2. Judging by the .stringify method that comes with JSON (commonly used for uploading data)

if(JSON.Stringify(c)=='{}'){
    console.log(''空)
}
   

3. Of course it is ES6 syntax, Object.key();

if(Object.key(obj).length==0){
    console.log( 'null object' )
}else{
    console.log( 'non-null object' )
}

  The Object.keys method is a method in JavaScript for traversing object properties.

The parameter it passes in is an object, and it returns an array, which contains all the property names of the object.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325015183&siteId=291194637
Recommended