7

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
  • 169,008
  • 28
  • 173
  • 236
Abhineet Sinha
  • 115
  • 1
  • 8

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
  • 376,160
  • 25
  • 347
  • 392
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
  • 169,008
  • 28
  • 173
  • 236
Deividas
  • 6,437
  • 2
  • 26
  • 27
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,817
  • 4
  • 20
  • 35