Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test for an empty JavaScript object?

After an AJAX request, sometimes my application may return an empty object, like:

var a = {}; 

How can I check whether that's the case?

like image 922
falmp Avatar asked Mar 25 '09 01:03

falmp


People also ask

How do you ask if an object is empty?

Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.

How do you check if all values in object is empty?

You can use Object. values() method to get all the object's values (as an array of object's values) and then check if this array of values contains null or "" values, with the help of _. includes method prvided by lodash library.

Is Empty object true in JS?

The empty object is not undefined. The only falsy values in JS are 0 , false , null , undefined , empty string, and NaN .


1 Answers

ECMA 5+:

// because Object.keys(new Date()).length === 0; // we have to do some additional check obj // 👈 null and undefined check && Object.keys(obj).length === 0 && Object.getPrototypeOf(obj) === Object.prototype 

Note, though, that this creates an unnecessary array (the return value of keys).

Pre-ECMA 5:

function isEmpty(obj) {   for(var prop in obj) {     if(Object.prototype.hasOwnProperty.call(obj, prop)) {       return false;     }   }    return JSON.stringify(obj) === JSON.stringify({}); } 

jQuery:

jQuery.isEmptyObject({}); // true 

lodash:

_.isEmpty({}); // true 

Underscore:

_.isEmpty({}); // true 

Hoek

Hoek.deepEqual({}, {}); // true 

ExtJS

Ext.Object.isEmpty({}); // true 

AngularJS (version 1)

angular.equals({}, {}); // true 

Ramda

R.isEmpty({}); // true 
like image 154
16 revs, 16 users 51% Avatar answered Sep 30 '22 10:09

16 revs, 16 users 51%