'How to check if an object is empty? [javascript]
I need to evaluate if an object is empty.
For example suppose I have an object:
var home = ....; // this is an object and after I print it
console.log(home) // the result of this option is []
//now I need to check if a object is empty or null
if( home == null || home == undefined )
{
// I don't know specify how object is empty
}
How can I detect whether or not the above object home is null/empty?
Solution 1:[1]
To check for an empty array
if (!arr.length) {
// if the array is empty
}
and for an object (check that it has no keys)
if (!Object.keys(obj).length) {
// if the object is empty
}
Solution 2:[2]
Only way I see so far may be ({}).toSource() === o.toSource()
Example:
var y = {a: 't'};
window.console.log(({}).toSource() === y.toSource());
delete y.a;
window.console.log(({}).toSource() === y.toSource());
EDIT : Oh, nicely found, Andy.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andy |
| Solution 2 | capqch |
