Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test whether object "isEmpty()" if Object.prototype was modified?

I want to test whether an object is empty: {}. The following is typically used:

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

But suppose the Object prototype was added to as follows:

Object.prototype.Foo = "bar";

Tests:

alert(isEmpty({}));              // true
Object.prototype.Foo = "bar";
alert({}.Foo);                   // "bar" oh no...
alert(isEmpty({}));              // true  ...**huh?!**

I tried to nuke the object's prototype, change it's constructor, and all manner of such hacks. Nothing worked, but maybe I did it wrong (probable).

like image 838
Peter Marks Avatar asked Jan 03 '12 05:01

Peter Marks


Video Answer


1 Answers

Just remove the obj.hasOwnProperty filter:

function isEmpty(obj) {
  for (var prop in obj) {
    return false;
  }
  return true;
}

DEMO

This way it will also tell you if contains any properties or if anything is in the prototype chain, if that's what you want.

Alternatively you can change

if (obj.hasOwnProperty(prop))

to

if (!obj.hasOwnProperty(prop))

if you only want to know if something is messing with it's prototype.

like image 69
qwertymk Avatar answered Sep 20 '22 07:09

qwertymk