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){ if(obj.hasOwnProperty(propName)){ 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({}) true >>> TM.isEmptyObject({1:2}) false >>> TM.isEmptyObject([]) true >>> TM.isEmptyObject([1,2]) false
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