Monday 18 October 2010

Detecting if a JSON object is empty in Javascript

I recently need to verify if an object passed back from the server had data in it, or was empty.
Imagine my surprise when I realised there is no simple way of acheiving this.

Anyway, I wrote a nice simple and fast method to do this.

function isEmptyObject(obj){
        for(var propName in obj){
                return false;
        return true;

isObjectEmpty iterates through the properties of an object, checks that the property being checked belongs to the object directly, ie: does not come from a prototype, and returns false.
If there are no properties belonging to the object, then it returns true.

The nice thing, is that it works on Arrays too.

>>> TM.isEmptyObject({})
>>> TM.isEmptyObject({1:2})
>>> TM.isEmptyObject([])
>>> TM.isEmptyObject([1,2])

Just be careful, it will fail on any extended object, as the extended function will probably have been put directly into the object itself.

No comments:

Post a Comment