After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
Join Stack Overflow to learn, share knowledge, and build your career.
After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
Object.keys(obj).length === 0 && obj.constructor === Object
Pre-ECMA 5:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return JSON.stringify(obj) === JSON.stringify({});
}
jQuery.isEmptyObject({}); // true
_.isEmpty({}); // true
_.isEmpty({}); // true
Hoek.deepEqual({}, {}); // true
Ext.Object.isEmpty({}); // true
angular.equals({}, {}); // true
R.isEmpty({}); // true
Object.keys(new Date()).length === 0; so this answer can be misleading.
– cjbarth
Mar 1 '16 at 16:34
(new Date()).constructor === Date, or conversely, ({}).constructor === Object.
– John Nelson
Apr 15 '16 at 12:22
Object.keys() doesn't check non-enumerable properties, or symbols. You need to use Object.getOwnPropertyNames() and Object.getOwnPropertySymbols() instead. Also, Object.getPrototypeOf() is the correct way to get an object's prototype. obj.constructor can be easily forged. Example: function Foo() {} Foo.prototype.constructor = Object; (new Foo()).constructor === Object // true.
– Jesse
Apr 9 at 9:22
There's no easy way to do this. You'll have to loop over the properties explicitly:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
If ECMAScript 5 support is available, you can use Object.keys() instead:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
isEmpty(), so it should return false if it has a property
– Christoph
May 6 '10 at 16:31
For those of you who have the same problem but uses jQuery, you can use jQuery.isEmptyObject.
underscore.js...
– BadHorsie
Jul 7 '15 at 15:35
You can use Underscore.js.
_.isEmpty({}); // true
This is my preferred solution:
var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
Object.keys(new Date()).length === 0; so this answer can be misleading.
– cjbarth
Mar 1 '16 at 16:36
if(Object.getOwnPropertyNames(obj).length === 0){
//is empty
}
see http://bencollier.net/2011/04/javascript-is-an-object-empty/
Object.getOwnPropertyNames(new Date()).length === 0; so this answer can be misleading.
– cjbarth
Mar 1 '16 at 16:37
How about using JSON.stringify? It is almost available in all modern browsers.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:
function isEmptyObject(obj) {
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
return false;
}
}
return true;
}
I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.
And what I did was, used the following condition, and it worked for me.
var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
//Code here..
}
For not equal to, use this : JSON.stringify(obj) !== '{}'
Check out this JSFiddle
There is a simple way if you are on a newer browser.
Object.keys(obj).length == 0
keys property come from?
– user663031
Sep 3 '14 at 13:23
Object.keys is a standard method but objects do not have a keys property. So this code will report any object as empty except it accidentally happens to have a property named key with a value which again as a property named length which is not zero. Horrible!
– scravy
Aug 5 '15 at 14:45
Object.keys(new Date()).length === 0; so this answer can be misleading.
– cjbarth
Mar 1 '16 at 16:40
I've created a complete function to determine if object is empty.
It uses Object.keys from ECMAScript 5 (ES5) functionality if possible to achieve the best performance (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).
/**
* Returns true if specified object has no properties,
* false otherwise.
*
* @param {object} object
* @returns {boolean}
*/
function isObjectEmpty(object)
{
if ('object' !== typeof object) {
throw new Error('Object must be specified.');
}
if (null === object) {
return true;
}
if ('undefined' !== Object.keys) {
// Using ECMAScript 5 feature.
return (0 === Object.keys(object).length);
} else {
// Using legacy compatibility mode.
for (var key in object) {
if (object.hasOwnProperty(key)) {
return false;
}
}
return true;
}
}
Here's the Gist for this code.
And here's the JSFiddle with demonstration and a simple test.
I hope it will help someone. Cheers!
null object.
– user663031
Sep 3 '14 at 13:24
Object.keys(new Date()).length === 0; so this answer can be misleading.
– cjbarth
Mar 1 '16 at 16:35
Just a workaround. Can your server generate some special property in case of no data?
For example:
var a = {empty:true};
Then you can easily check it in your AJAX callback code.
Another way to check it:
if (a.toSource() === "({})") // then 'a' is empty
EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.
toSource() is non-standard and doesn't work in IE or Opera (and potentially other browsers I didn't check)
– Christoph
Mar 25 '09 at 12:21
toSource property in section 15.2.4; according to MDC, it was introduced in JS1.3 (i.e. Netscape Navigator 4.06), but it's NOT in ECMA-262, 3rd edition!
– Christoph
Mar 25 '09 at 22:47
toSource() is a horrible way to do this (as is JSON.encode()). It needs to build a string representing your entire object to just check if it's empty. There's the overhead of converting things to strings, but moreover it will need to convert a million things if your object has a million properties, while actually just looking at one will let you know that it is not empty.
– Jasper
Aug 12 '14 at 8:42
I am using this.
function isObjectEmpty(object)
{
var isEmpty = true;
for(keys in object)
{
isEmpty = false;
break; // exiting since we found that the object is not empty
}
return isEmpty;
}
Eg:
var myObject = {}; // Object is empty
var isEmpty = isObjectEmpty(myObject); // will return true;
// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"};
// check if the object is empty
isEmpty = isObjectEmpty(myObject); // will return false;
Update
OR
you can use the jQuery implementation of isEmptyObject
function isEmptyObject ( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
}
Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.
Tested under Node, Chrom, Firefox and IE 9, it becomes evident that for most use cases:
Bottom line performance wise, use:
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
or
function isEmpty(obj) {
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }
return true;
}
See detailed testing results and test code at Is object empty?
You could check for the count of the Object keys:
if (Object.keys(a).length > 0) {
// not empty
}
function isEmpty(obj) {
for(var i in obj) { return false; }
return true;
}
Object with a method through the prototype chain, because that's enumerable and the for in statement loops through enumerable properties.
– Török Gábor
Apr 24 '09 at 13:20
jQuery have special function isEmptyObject() for this case:
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
Read more on http://api.jquery.com/jQuery.isEmptyObject/
you can use this simple code that did not use jQuery or other libraries
var a=({});
//check is an empty object
if(JSON.stringify(a)=='{}') {
alert('it is empty');
} else {
alert('it is not empty');
}
JSON class and it's functions (parse and stringify) are very usefull but has some problems with IE7 that you can fix it with this simple code http://www.json.org/js.html.
Other Simple Way (simplest Way) :
you can use this way without using jQuery or JSON object.
var a=({});
function isEmptyObject(obj) {
if(typeof obj!='object') {
//it is not object, so is not empty
return false;
} else {
var x,i=0;
for(x in obj) {
i++;
}
if(i>0) {
//this object has some properties or methods
return false;
} else {
//this object has not any property or method
return true;
}
}
}
alert(isEmptyObject(a)); //true is alerted
JSON.stringify solution fails if object contains non-stringifiable properties such as functions or "undefined", although granted that's an edge case.
– user663031
Sep 3 '14 at 13:29
If jQuery and the web browser is not available, there is also an isEmpty function in underscore.js.
_.isEmpty({}) // returns true
Additionally, it does not assume the input parameter to be an object. For a list or string or undefined, it will also turn the correct answer.
Best way that I found:
function isEmpty(obj)
{
if (!obj)
{
return true;
}
if (!(typeof(obj) === 'number') && !Object.keys(obj).length)
{
return true;
}
return false;
}
Works for:
t1: {} -> true
t2: {0:1} -: false
t3: [] -> true
t4: [2] -> false
t5: null -> true
t6: undefined -> true
t7: "" -> true
t8: "a" -> false
t9: 0 -> true
t10: 1 -> false
if (!obj && obj !== 0).
– mjwrazor
Jun 1 '17 at 15:10
My take:
function isEmpty(obj) {
return !Object.keys(obj).length > 0;
}
var a = {a:1, b:2}
var b = {}
console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true
Just, I don't think all browsers implement Object.keys() currently.
Object.keys(new Date()).length === 0; so this answer can be misleading.
– cjbarth
Mar 1 '16 at 16:40
The following example show how to test if a JavaScript object is empty, if by empty we means has no own properties to it.
The script works on ES6.
const isEmpty = (obj) => {
if (obj === null ||
obj === undefined ||
Array.isArray(obj) ||
typeof obj !== 'object'
) {
return true;
}
return Object.getOwnPropertyNames(obj).length === 0 ? true : false;
};
console.clear();
console.log('-----');
console.log(isEmpty('')); // true
console.log(isEmpty(33)); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello')); // true
console.log(isEmpty([1, 2, 3])); // true
console.log(isEmpty({ test: 1 })); // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date())); // true
console.log(isEmpty(Infinity)); // true
console.log(isEmpty(null)); // true
console.log(isEmpty(undefined)); // true
A simple loop:
var is_empty = true;
for(var i in obj) {
is_empty = false;
break;
}
Another simple, pure JS way :)
if (JSON.stringify(pathParams) === '{}')
In addition to Thevs answer:
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
it's jquery + jquery.json
$.isEmptyObject(), don't waste cycles with non-obvious conversions.
– skierpage
Feb 7 '15 at 2:17
Caveat! Beware of JSON's limitiations.
javascript:
obj={ f:function(){} };
alert( "Beware!! obj is NOT empty!\n\nobj = { f:function(){} }" +
"\n\nJSON.stringify( obj )\n\nreturns\n\n" +
JSON.stringify( obj ) );
displays
Beware!! obj is NOT empty!
obj = { f:function(){} }
JSON.stringify( obj )
returns
{}
Sugar.JS provides extended objects for this purpose. The code is clean and simple:
Make an extended object:
a = Object.extended({})
Check it's size:
a.size()
Another alternative is to use is.js (14kB) as opposed to jquery (32kB), lodash (50kB), or underscore (16.4kB). is.js proved to be the fastest library among aforementioned libraries that could be used to determine whether an object is empty.
http://jsperf.com/check-empty-object-using-libraries
Obviously all these libraries are not exactly the same so if you need to easily manipulate the DOM then jquery might still be a good choice or if you need more than just type checking then lodash or underscore might be good. As for is.js, here is the syntax:
var a = {};
is.empty(a); // true
is.empty({"hello": "world"}) // false
Like underscore's and lodash's _.isObject(), this is not exclusively for objects but also applies to arrays and strings.
Under the hood this library is using Object.getOwnPropertyNames which is similar to Object.keys but Object.getOwnPropertyNames is a more thorough since it will return enumerable and non-enumerable properties as described here.
is.empty = function(value) {
if(is.object(value)){
var num = Object.getOwnPropertyNames(value).length;
if(num === 0 || (num === 1 && is.array(value)) || (num === 2 && is.arguments(value))){
return true;
}
return false;
} else {
return value === '';
}
};
If you don't want to bring in a library (which is understandable) and you know that you are only checking objects (not arrays or strings) then the following function should suit your needs.
function isEmptyObject( obj ) {
return Object.getOwnPropertyNames(obj).length === 0;
}
This is only a bit faster than is.js though just because you aren't checking whether it is an object.
The correct answer is:
const isEmptyObject = obj =>
Object.getOwnPropertyNames(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0 &&
Object.getPrototypeOf(obj) === Object.prototype;
This checks that:
Object.prototype.In other words, the object is indistinguishable from one created with {}.
this one line code helps
var a = {}; //if empty returns false
(Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(a).length != 0 : (function(){for(var key in a) break; return (key != null) && (key != undefined);})()) //Returns False
var a = {b:2} //if not empty returns true
(Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(a).length != 0 : (function(){for(var key in a) break; return (key != null) && (key != undefined);})()) //Returns true
Object.getOwnPropertyNames is implemented in ECMA-5. the above line works in older browsers with a fallback function.
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?