How do I test for an empty JavaScript object?

After an AJAX request, sometimes my application may return an empty object, like:

var a = {};

How can I check whether that's the case?


ECMA 5+:

// because Object.keys(new Date()).length === 0;
// we have to do some additional check
Object.keys(obj).length === 0 && obj.constructor === Object

Pre-ECMA 5:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return JSON.stringify(obj) === JSON.stringify({});
}

jQuery:

jQuery.isEmptyObject({}); // true

lodash:

_.isEmpty({}); // true

Underscore:

_.isEmpty({}); // true

Hoek

Hoek.deepEqual({}, {}); // true

ExtJS

Ext.Object.isEmpty({}); // true

AngularJS (version 1)

angular.equals({}, {}); // true

Ramda

R.isEmpty({}); // true

There's no easy way to do this. You'll have to loop over the properties explicitly:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}

If ECMAScript 5 support is available, you can use Object.keys() instead:

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

对于那些有相同问题但使用jQuery的人,可以使用jQuery.isEmptyObject。

链接地址: http://www.djcxy.com/p/5430.html

上一篇: 将JS对象转换为JSON字符串

下一篇: 如何测试空的JavaScript对象?