js judges empty objects and empty arrays

It is often necessary to judge data during business processing. Here we introduce the judgment methods of empty objects and empty arrays.

Judgment of empty array

if(Array.prototype.isPrototypeOf(obj)&&obj.length === 0){return true;}

Null object judgment

if(Object.prototype.isPrototypeOf(obj)&&Object.keys(obj).length === 0){return true;}

The isPrototypeOf() method is used to test whether an object exists in the prototype chain of another object. That is to determine whether Object exists in the prototype chain of obj.

The Object.keys() method returns an array composed of the enumerable properties of a given object. The sequence of the property names in the array for…in is the same as the return order when looping through the object. This method belongs to the ES5 standard, IE9 and above And other modern browsers are supported. If you unfortunately need to be compatible with browsers below IE9, use for…in instead. However, for…in will also enumerate the properties on the object prototype chain, so another judgment is needed.

for(var key in obj) {
    if(obj.hasOwnProperty(key)) {
        return false;
    }
}

There is also a very special way to check for empty objects or empty arrays

if(JSON.stringify(obj) === '{}'){return true;}
 
if(JSON.stringify(obj) === '[]'){return true;}

Leave a Reply