266

Assuming I declare

var ad = {}; 

How can I check whether this object will contain any user-defined properties?

17 Answers 17

452

You can use the built in Object.keys method to get a list of keys on an object and test its length.

var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values

if(Object.keys(x).length){
 // Your code here if x has some properties  
}
Sign up to request clarification or add additional context in comments.

9 Comments

This right here is the correct answer. The accepted answer above is a work-around and is more expensive than just checking the number of keys; this makes way more sense.
Object.keys("mystring"); yields keys as well which I think is undesirable. This answer is incomplete in my opinion.
@MikedeKlerk please read it carefully it's not Object.keys("mystring"); it's Object.keys(objectVariableName) which will return array of all the keys in object. ex : { 'x' : 'abc', 'y' : 'def' } it will be ['x' , 'y']
@DhavalChaudhary Thanks for your reply to my comment. When I try this code var str = "MyString"; Object.keys(str);, the console outputs 8 keys, from 0 to 7, for each character. Or do I still not understand the answer.
@MikedeKlerk but it's only solution for objects not for strings pls refer question.
|
122

What about making a simple function?

function isEmptyObject(obj) {
  for(var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
      return false;
    }
  }
  return true;
}

isEmptyObject({}); // true
isEmptyObject({foo:'bar'});  // false

The hasOwnProperty method call directly on the Object.prototype is only to add little more safety, imagine the following using a normal obj.hasOwnProperty(...) call:

isEmptyObject({hasOwnProperty:'boom'});  // false

Note: (for the future) The above method relies on the for...in statement, and this statement iterates only over enumerable properties, in the currently most widely implemented ECMAScript Standard (3rd edition) the programmer doesn't have any way to create non-enumerable properties.

However this has changed now with ECMAScript 5th Edition, and we are able to create non-enumerable, non-writable or non-deletable properties, so the above method can fail, e.g.:

var obj = {};
Object.defineProperty(obj, 'test', { value: 'testVal', 
  enumerable: false,
  writable: true,
  configurable: true
});
isEmptyObject(obj); // true, wrong!!
obj.hasOwnProperty('test'); // true, the property exist!!

An ECMAScript 5 solution to this problem would be:

function isEmptyObject(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

The Object.getOwnPropertyNames method returns an Array containing the names of all the own properties of an object, enumerable or not, this method is being implemented now by browser vendors, it's already on the Chrome 5 Beta and the latest WebKit Nightly Builds.

Object.defineProperty is also available on those browsers and latest Firefox 3.7 Alpha releases.

10 Comments

What is the advantage to Object.prototype.hasOwnProperty.call(obj, prop) over obj.hasOwnProperty(prop)?
@Casey, edited, if an object overrides the hasOwnProperty property, the function might crash... I know I'm a little bit paranoid... but sometimes you don't know in which kind of environment your code will be used, but you know what method you want to use...
+1 for answering this question... and other questions of the future! :)
Note there is also a bug in IE where if you have a property with a name that matches a non-enumerable property in Object.prototype, it doesn't get enumerated by for...in. So isEmptyObject({toString:1}) will fail. This is one of the unfortunate reasons you can't quite use Object as a general-purpose mapping.
@MichaelMartin-Smucker— keys only returns enumerable own properties, so not suitable here.
|
98

You can loop over the properties of your object as follows:

for(var prop in ad) {
    if (ad.hasOwnProperty(prop)) {
        // handle prop as required
    }
}

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

Edit

From the comments: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment

6 Comments

Hi Daniel, actually I'm seeking a device to check whether an object contains user-defined properies or not. Not to check whether a specific property exist.
@Ricky: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment.
I think these days using Object.keys would be the easiest: var a = [1,2,3];a.something=4;console.log(Object.keys(a)) Because it's already part of ECMA 5 you can safely shim it: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Note that "these days" with ES5, native objects can have non–enumerable own properties, e.g. Object.defineProperty(obj, 'foo', {enumerable:false, value:'foo'}).
This solution is a way to check for keys that exist, but the true, efficient, and most-correct answer is below using Object.keys(x).length. You don't need to make your own function, one already exists!
|
62

With jQuery you can use:

$.isEmptyObject(obj); // Returns: Boolean

As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty).

With ECMAScript 5th Edition in modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

var obj = { blah: 1 };
var isEmpty = !Object.keys(obj).length;

Or plain old JavaScript:

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

Comments

46

Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:

var ad = {}; 
Object.keys(ad).length;//this will be 0 in this case

Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Comments

15

If you're using underscore.js then you can use the _.isEmpty function:

var obj = {};
var emptyObject = _.isEmpty(obj);

1 Comment

Just for anyone passing by, this is not a method dedicated to objects. _.isEmpty([]) // true Be sure to check first: stackoverflow.com/a/22482737/1922747
11

If you are willing to use lodash, you can use the some method.

_.some(obj) // returns true or false

See this small jsbin example

3 Comments

var x = [1,2] // true
@damionjn I added your code to the example. I see your point with the array returning the wrong answer, but OP initially declared a variable as an object so I believe its alright to assume this. There is an answer above which uses the underscores isEmpty method (lodash has the same method). That answer has the exact same issue. If you give isEmpty a non empty array you will also get the wrong result.
Fair enough, but we should be providing answers with all bases covered to be sure of best practices. You're right, I passed right by his answer without any criticism. Just for anyone passing by, this is not a method dedicated to objects. _.some([1, 2]) // true Be sure to check first: stackoverflow.com/a/13356338/1922747
6
for (var hasProperties in ad) break;
if (hasProperties)
    ... // ad has properties

If you have to be safe and check for Object prototypes (these are added by certain libraries and not there by default):

var hasProperties = false;
for (var x in ad) {
    if (ad.hasOwnProperty(x)) {
        hasProperties = true;
        break;
    }
}
if (hasProperties)
    ... // ad has properties

2 Comments

in your solution there is no filtering for unwanted prototype properties, that means it might be misbehaving when using a library like Prototype.js or an unexperienced user added additional prototype properties to the object. Check out Daniels solution on this page.
You don't have to use a library or be unexperienced to extend an object's prototype. Some experienced programmers do this all the time.
2
for(var memberName in ad)
{
  //Member Name: memberName
  //Member Value: ad[memberName]
}

Member means Member property, member variable, whatever you want to call it >_>

The above code will return EVERYTHING, including toString... If you only want to see if the object's prototype has been extended:

var dummyObj = {};  
for(var memberName in ad)
{
  if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
  //Member Name: memberName
  //Member Value: ad[memberName]

}

Note A: We check to see if the dummy object's member has the same type as our testing object's member. If it is an extend, dummyobject's member type should be "undefined"

6 Comments

Hi, can I just know whether an object contain properties or not? Thanks
in your solution there is no filtering for unwanted prototype properties, that means it might be misbehaving when using a library like Prototype.js or an unexperienced user added additional prototype properties to the object.
check out Daniels solution on this page - its less error-prone!
Your first code block does not cover it at all. the second code block misbehaves if I add a variable to the "ad" object which is undefined. Really, check out Daniels answer, it's the only correct one and fast, as it uses a native implementation called "hasOwnProperty".
@Ricky: If you want to check whether an object contains properties, you can simply use the example in my answer: stackoverflow.com/questions/2673121/…. If the code reaches the comment, your object would not have any direct properties. If not, it would.
|
2
var hasAnyProps = false; for (var key in obj) { hasAnyProps = true; break; }
// as of this line hasAnyProps will show Boolean whether or not any iterable props exist

Simple, works in every browser, and even though it's technically a loop for all keys on the object it does NOT loop through them all...either there's 0 and the loop doesn't run or there is some and it breaks after the first one (because all we're checking is if there's ANY...so why continue?)

Comments

2

ES6 function

/**
 * Returns true if an object is empty.
 * @param  {*} obj the object to test
 * @return {boolean} returns true if object is empty, otherwise returns false
 */
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0

Examples:


let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false

Comments

1

When sure that the object is a user-defined one, the easiest way to determine if UDO is empty, would be the following code:

isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};

Even though this method is (by nature) a deductive one, - it's the quickest, and fastest possible.

a={};
isEmpty(a) >> true

a.b=1
isEmpty(a) >> false 

p.s.: !don't use it on browser-defined objects.

3 Comments

...return 0; return 1}; would be the same ?
@pike no, return!1;return!0 is the same as return false;return true
this is the answer with the shortest code. isEmpty=(x,p)=>{for(p in x)return!1;return!0};
1

You can use the following:

Double bang !! property lookup

var a = !![]; // true
var a = !!null; // false

hasOwnProperty This is something that I used to use:

var myObject = {
  name: 'John',
  address: null
};
if (myObject.hasOwnProperty('address')) { // true
  // do something if it exists.
}

However, JavaScript decided not to protect the method’s name, so it could be tampered with.

var myObject = {
  hasOwnProperty: 'I will populate it myself!'
};

prop in myObject

var myObject = {
  name: 'John',
  address: null,
  developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.

typeof

if (typeof myObject.name !== 'undefined') {
  // do something
}

However, it doesn't check for null.

I think this is the best way.

in operator

var myObject = {
  name: 'John',
  address: null
};

if('name' in myObject) {
  console.log("Name exists in myObject");
}else{
  console.log("Name does not exist in myObject");
}

result:

Name exists in myObject

Here is a link that goes into more detail on the in operator: Determining if an object property exists

Comments

1

Very late answer, but this is how you could handle it with prototypes.

Array.prototype.Any = function(func) {
    return this.some(func || function(x) { return x });
}

Object.prototype.IsAny = function() {
    return Object.keys(this).Any();
}

Comments

0

Object.hasOwn is a new static method (not fully supported by all browsers yet) which checks if the specified object has the indicated property as his own property and return true if that is the case. It will return false if the property is either inherited or does not exist on that object.

You can iterate through the object properties and check if they are indeed own properties

for (let property in ad) {
   if (Object.hasOwn(ad, property)) {
    // handle your code for object own properties here
  }
}   

More about Object.hasOwn - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/

Browser compatibility here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

1 Comment

No Safari (iOS or Macos) support yet =(
0

I'm not sure if this is a good approach but I use this condition to check if an object has or hasn't any property. Could be easily transformed into a function.

const obj = {};
    
if(function(){for (key in obj){return true}return false}())
{
  //do something;
}
else
{
  //do something else;
}
    
//Condition could be shorted by e.g. function(){for(key in obj){return 1}return 0}()

Comments

-4

How about this?

var obj = {},
var isEmpty = !obj;
var hasContent = !!obj

2 Comments

This answer doesn't answer the question. OP is asking if an object contains user-defined properties - your answer checks if the object itself will convert to a Boolean false value.
...and I also realized later that James already included this option in his answer. Sorry guys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.