Organizational Research By

Surprising Reserch Topic

how do i test for an empty javascript object


how do i test for an empty javascript object  using -''

asked Sep 9, 2015 by rajesh
0 votes
10 views



Related Hot Questions

23 Answers

0 votes

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;
}
answered Sep 9, 2015 by rajesh
0 votes

How about using JSON.stringify? It is almost available in all modern browsers.

function isEmptyObject(obj){
    return JSON.stringify(obj) === '{}';
}
answered Sep 9, 2015 by rajesh
0 votes

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) {
        return false;
    }
    return true;
}
answered Sep 9, 2015 by rajesh
0 votes
  1. 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.

  2. 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.

answered Sep 9, 2015 by rajesh
0 votes

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

answered Sep 9, 2015 by rajesh
0 votes

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;

from here

Update

OR

you can use the jQuery implementation of isEmptyObject

function isEmptyObject ( obj ) {
        var name;
        for ( name in obj ) {
            return false;
        }
        return true;
    }
answered Sep 9, 2015 by rajesh
0 votes

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 possible (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).

Solution

/**
 * 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!

answered Sep 9, 2015 by rajesh
0 votes

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/

answered Sep 9, 2015 by rajesh
0 votes


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
answered Sep 9, 2015 by rajesh
0 votes

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.

answered Sep 9, 2015 by rajesh
0 votes

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.

answered Sep 9, 2015 by rajesh
0 votes

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

    {}
answered Sep 9, 2015 by rajesh
0 votes

ECMA 5+:

Object.keys({}).length; // 0

Pre-ECMA 5:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}

jQuery:

jQuery.isEmptyObject({}); // true

lodash:

_.isEmpty({}); // true

Underscore:

_.isEmpty({}); // true
answered Sep 9, 2015 by rajesh
0 votes

In addition to Thevs answer:

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

it's jquery + jquery.json

answered Sep 9, 2015 by rajesh
0 votes

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.

JSFiddler

answered Sep 9, 2015 by rajesh
0 votes

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()
answered Sep 9, 2015 by rajesh
0 votes
    isEmpty = function(obj) {
      if (obj == null) return true;
      if (obj.constructor.name == "Array" || obj.constructor.name == "String") return obj.length === 0;
      for (var key in obj) if (isEmpty(obj[key])) return true;
      return false;
    }

This will check the emptiness of String, Array or Object (Maps).

Usage :

var a = {"a":"xxx","b":[1],"c":{"c_a":""}}
isEmpty(a); // true, because a.c.c_a is empty.
isEmpty("I am a String"); //false
answered Sep 9, 2015 by rajesh
0 votes

As of jQuery 1.4 isEmptyObject() method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty). The argument should always be a plain JavaScript Object as other types of object (DOM elements, primitive strings/numbers, host objects) may not give consistent results across browsers. To determine if an object is a plain JavaScript object, use $.isPlainObject().

jQuery.isPlainObject({}) // true

jQuery.isPlainObject( "test" ) // false

Jquery api

answered Sep 9, 2015 by rajesh
0 votes

If you are checking object's emptiness for going in some code block, add a break after first foreach round, the code looks as simple as if statement.

 for(key in obj){

 //your work here.

 break;
 }
answered Sep 9, 2015 by rajesh
0 votes

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.

answered Sep 9, 2015 by rajesh

...