BartlomiejSkwira
10/16/2013 - 11:15 AM

object/hash is empty

object/hash is empty

#check support
Object.keys(obj).length === 0
#or
if (Object.getOwnPropertyNames(obj).length > 0) return false;

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

function is_empty(obj) {

    // null and undefined are empty
    if (obj == null) return true;
    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length && obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    for (var key in obj) {
        if (hasOwnProperty.call(obj, key))    return false;
    }

    // Doesn't handle toString and toValue enumeration bugs in IE < 9

    return true;
}

// Examples
console.log(
    is_empty(""), // True
    is_empty([]), // True
    is_empty({}), // True
    is_empty({length: 0, custom_property: []}), // True

    is_empty("Hello"), // False
    is_empty([1,2,3]), // False
    is_empty({test: 1}), // False
    is_empty({length: 3, custom_property: [1,2,3]}) // False
);