Вопрос: Как проверить наличие пустого объекта JavaScript?


После запроса AJAX иногда мое приложение может возвращать пустой объект, например:

var a = {};

Как я могу проверить, так ли это?


1815


источник


Ответы:


ECMA 5+ :

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

Предварительная 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

Нижнее подчеркивание :

_.isEmpty({}); // true

Хук

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

ExtJS

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

AngularJS (версия 1)

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

Ramda

R.isEmpty({}); // true

2943



Нет простого способа сделать это. Вы должны будете явно перекрыть свойства:

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

    return true;
}

Если Поддержка ECMAScript 5 доступно, вы можете использовать Object.keys()вместо:

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

742



Для тех из вас, кто имеет такую ​​же проблему, но использует jQuery, вы можете использовать jQuery.isEmptyObject ,


538



You can use Underscore.js.

_.isEmpty({}); // true

182



This is my preferred solution:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty

173



if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

see http://bencollier.net/2011/04/javascript-is-an-object-empty/


102



How about using JSON.stringify? It is almost available in all modern browsers.

function isEmptyObject(obj){
    return JSON.stringify(obj) === '{}';
}

63



Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}

50



I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.

And what I did was, used the following condition, and it worked for me.

var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
   //Code here..
}

For not equal to, use this : JSON.stringify(obj) !== '{}'

Check out this JSFiddle


38



I've created a complete function to determine if object is empty.

It uses Object.keys from ECMAScript 5 (ES5) functionality if possible to achieve the best performance (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).

Solution

/**
 * Returns true if specified object has no properties,
 * false otherwise.
 *
 * @param {object} object
 * @returns {boolean}
 */
function isObjectEmpty(object)
{
    if ('object' !== typeof object) {
        throw new Error('Object must be specified.');
    }

    if (null === object) {
        return true;
    }

    if ('undefined' !== Object.keys) {
        // Using ECMAScript 5 feature.
        return (0 === Object.keys(object).length);
    } else {
        // Using legacy compatibility mode.
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }
}

Here's the Gist for this code.

And here's the JSFiddle with demonstration and a simple test.

I hope it will help someone. Cheers!


20



There is a simple way if you are on a newer browser. Object.keys(obj).length == 0


19



  1. Just a workaround. Can your server generate some special property in case of no data?

    For example:

    var a = {empty:true};
    

    Then you can easily check it in your AJAX callback code.

  2. Another way to check it:

    if (a.toSource() === "({})")  // then 'a' is empty
    

EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.


17