Reputation: 11984
JSFiddle: https://jsfiddle.net/pd08dgxu/1/
I need to check whether a JavaScript object is empty or not. Suppose, in this fiddle, Obj1 is not empty (it contains the fields below) but Obj2 is {}
.
In both cases, when I check obj1.length
or obj2.length
, I get Undefined (see alert). Shouldn't we check for existence by using the .length
operator on all variables, whether strings or complex objects?
function getObject() {
return { 'color' : 'red',
'title' : 'my title'
};
}
var myObj1 = getObject();
var myObj2 = {}; //empty object
alert('myObj1 Length = ' + myObj1.length + ' myObj2 Length = ' + myObj2.length);
Upvotes: 0
Views: 841
Reputation: 5955
Here is my conventional JavaScript singleton which is a part of all my util. libs.
function isEnum(x){for(var i in x)return!0;return!1};
And it's faster than Object.keys in any aspect. Will work correctly in case you've accidentally dropped an Array in its argument instead of an Object.
It's use is exactly what you need it for to check if the object is empty or enumerable before deciding to iterate it or not.
Upvotes: 0
Reputation: 957
The length
property only works like that on Arrays.
To get the number of properties on any object, you can use the Object.keys
method, which returns an array of all the property-names on an object. Like this: Object.keys(Obj).length
.
Upvotes: 1
Reputation: 3233
You cannot check the object's existance using obj.length
.
You have to count the number of key
s.
Try Object.keys(Obj).length
function getObject() {
return { 'color' : 'red',
'title' : 'my title'
};
}
var myObj1 = getObject();
var myObj2 = {}; //empty object
console.log('myObj1 Length = ' + Object.keys(myObj1).length + ' myObj2 Length = ' + Object.keys(myObj2).length);
Upvotes: 1