6

This is similar to what I have been trying to do,

var obj = {};
if(obj){
//do something
}

What i want to do is that the condition should fail when the object is empty.

I tried using JSON.stringify(obj) but it still has curly braces('{}') within it.

mplungjan
  • 155,085
  • 27
  • 166
  • 222

3 Answers3

7

You could use Object.keys and check the length of the array of the own keys.

function go(o) {
    if (Object.keys(o).length) {
        console.log(o.foo);
    }
}

var obj = {};

go(obj);
obj.foo = 'bar';
go(obj);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
5

You can check if the object is empty, i.e. it has no properties, using

Object.keys(obj).length === 0

Object.keys() returns all properties of the object in an array.

If the array is empty (.length === 0) it means the object is empty.

mplungjan
  • 155,085
  • 27
  • 166
  • 222
Deividas Karzinauskas
  • 6,243
  • 2
  • 25
  • 26
0

You can use Object.keys(myObj).length to find out the length of object to find if the object is empty.

working example

    var myObj = {};
    if(Object.keys(myObj).length>0){
      // will not be called
      console.log("hello");
    }


   myObj.test = 'test';

    if(Object.keys(myObj).length>0){
      console.log("will be called");
    } 
See details of Object.keys
Abdullah Al Noman
  • 2,728
  • 1
  • 17
  • 35