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.

1
  • Try Object.keys(obj).length. Commented Mar 13, 2017 at 9:16

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer!
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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.