Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an empty object as a parameter to a conditional if loop [duplicate]

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.

like image 836
Abhineet Sinha Avatar asked Mar 13 '17 09:03

Abhineet Sinha


2 Answers

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);
like image 178
Nina Scholz Avatar answered Oct 03 '22 05:10

Nina Scholz


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.

like image 41
Deividas Karzinauskas Avatar answered Oct 03 '22 07:10

Deividas Karzinauskas