¿Cómo pruebo un objeto JavaScript vacío?


Después de una solicitud AJAX, a veces mi aplicación puede devolver un objeto vacío, como:

var a = {};

¿Cómo puedo comprobar si ese es el caso?

Author: robsch, 2009-03-25

30 answers

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

Subrayado:

_.isEmpty({}); // true

Hoek

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

ExtJS

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

AngularJS (versión 1)

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

Ramda

R.isEmpty({}); // true
 3275
Author: Adam Zerner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-13 18:45:25

No hay una manera fácil de hacer esto. Tendrás que hacer un bucle sobre las propiedades explícitamente:

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

    return true;
}

Si el soporte de ECMAScript 5 está disponible, puede usar Object.keys() en su lugar:

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}
 755
Author: Christoph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-29 10:30:56

Para aquellos que tienen el mismo problema pero usan jQuery, pueden usar jQuery.isEmptyObject .

 541
Author: Erik Töyrä,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-19 14:07:51

Esta es mi solución preferida:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
 189
Author: dhruvio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-12 07:46:49

Puede usar Subrayado.js .

_.isEmpty({}); // true
 186
Author: Baggz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-21 15:54:39
if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

Véase http://bencollier.net/2011/04/javascript-is-an-object-empty /

 104
Author: es cologne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-06 13:48:25

Qué tal usar JSON.stringify? Está casi disponible en todos los navegadores modernos.

function isEmptyObject(obj){
    return JSON.stringify(obj) === '{}';
}
 63
Author: Ateszki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-18 09:31:43

Vieja pregunta, pero acaba de tener el problema. Incluyendo JQuery no es realmente una buena idea si su único propósito es comprobar si el objeto no está vacío. En su lugar, solo profundiza en el código de jQuery, y obtendrás la respuesta:

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}
 52
Author: Jonathan Petitcolas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-22 17:32:50

Me encontré con una situación similar. No quería usar jQuery, y quería hacer esto usando Javascript puro.

Y lo que hice fue, usé la siguiente condición, y funcionó para mí.

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

Para no igual a, use esto: JSON.stringify(obj) !== '{}'

Mira esto JSFiddle

 43
Author: Anish Nair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-14 04:45:44

Hay una manera simple si está en un navegador más reciente. Object.keys(obj).length == 0

 24
Author: download,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-29 19:25:48

He creado una función completa para determinar si el objeto está vacío.

Utiliza Object.keys desde ECMAScript 5 (ES5) funcionalidad si es posible para lograr el mejor rendimiento (ver tabla de compatibilidad) y respaldo al enfoque más compatible para motores más antiguos (navegadores).

Solución

/**
 * 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;
    }
}

Aquí está la Esencia para este código.

Y aquí está el JSFiddle con demostración y una prueba simple.

Espero que ayudará a alguien. ¡Salud!

 20
Author: Slava Fomin II,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-25 23:42:07
  1. Solo una solución. ¿Puede su servidor generar alguna propiedad especial en caso de que no haya datos?

    Por ejemplo:

    var a = {empty:true};
    

    Entonces puede comprobarlo fácilmente en su código de devolución de llamada AJAX.

  2. Otra forma de comprobarlo:

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

EDITAR : Si utiliza cualquier biblioteca JSON (por ejemplo, JSON.js) entonces usted puede intentar JSON.función encode () y prueba el resultado contra una cadena de valor vacía.

 17
Author: Thevs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-04 12:40:11

Usando Objeto.llaves (obj).la longitud (como se sugirió anteriormente para ECMA 5+) es 10 veces más lenta para objetos vacíos! seguir con la vieja escuela (for...in) opción.

Probado en Node, Chrom, Firefox e IE 9, se hace evidente que para la mayoría de los casos de uso:

  • (for...in...) es la opción más rápida de usar!
  • Objeto.llaves (obj).la longitud es 10 veces más lenta para objetos vacíos
  • JSON.stringify (obj).la longitud es siempre la más lenta (no sorprendente)
  • Objeto.getOwnPropertyNames (obj).la longitud toma más tiempo que el objeto.llaves (obj).length puede ser mucho más largo en algunos sistemas.

En términos de rendimiento, use:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

O

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

Vea los resultados detallados de las pruebas y el código de prueba en ¿El objeto está vacío?

 16
Author: davidhadas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:31

Puede comprobar el número de claves del objeto:

if (Object.keys(a).length > 0) {
    // not empty
}
 16
Author: Ashutosh Ranjan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-30 12:22:50

Otra manera simple y pura de JS:)

if (JSON.stringify(pathParams) === '{}')

 15
Author: Leon Gaban,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-26 19:01:29

Estoy usando esto.

function isObjectEmpty(object)
{
  var isEmpty = true;
  for(keys in object)
  {
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  }
  return isEmpty;
}

Eg:

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;

// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 

// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;

Desde aquí

Update

O

Puede usar la implementación de jQuery de isEmptyObject

function isEmptyObject ( obj ) {
        var name;
        for ( name in obj ) {
            return false;
        }
        return true;
    }
 14
Author: kiranvj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-22 07:50:12
function isEmpty(obj) {
  for(var i in obj) { return false; }
  return true;
}
 10
Author: Lightness Races in Orbit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-01 08:26:19

JQuery tiene una función especial isEmptyObject() para este caso:

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

Leer más en http://api.jquery.com/jQuery.isEmptyObject/

 8
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-25 14:25:42


puede usar este código simple que no usó jQuery u otras bibliotecas

var a=({});

//check is an empty object
if(JSON.stringify(a)=='{}') {
    alert('it is empty');
} else {
    alert('it is not empty');
}

JSON clase y funciones (analizar y stringify) son muy útiles, pero tiene algunos problemas con IE7 que puedes solucionarlo con este simple código http://www.json.org/js.html.

Otra Manera Simple (Manera más simple) :
se puede usar de esta manera sin usar jQuery o JSON object.

var a=({});

function isEmptyObject(obj) {
    if(typeof obj!='object') {
        //it is not object, so is not empty
        return false;
    } else {
        var x,i=0;
        for(x in obj) {
            i++;
        }
        if(i>0) {
            //this object has some properties or methods
            return false;
        } else {
            //this object has not any property or method
            return true;
        }
    }
}

alert(isEmptyObject(a));    //true is alerted
 8
Author: iman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-03 04:34:43

La mejor manera que encontré:

function isEmpty(obj)
{
    if (!obj)
    {
        return true;
    }

    if (!(typeof(obj) === 'number') && !Object.keys(obj).length)
    {
        return true;
    }

    return false;
}

Funciona para:

    t1: {} -> true
    t2: {0:1} -: false
    t3: [] -> true
    t4: [2] -> false
    t5: null -> true
    t6: undefined -> true
    t7: "" -> true
    t8: "a" -> false
    t9: 0 -> true
    t10: 1 -> false
 8
Author: DiegoAraujo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-15 13:32:58

El siguiente ejemplo muestra cómo probar si un objeto JavaScript está vacío, si por vacío queremos decir que no tiene propiedades propias.

El script funciona en ES6.

const isEmpty = (obj) => {
    if (obj === null ||
        obj === undefined ||
        Array.isArray(obj) ||
        typeof obj !== 'object'
    ) {
        return true;
    }
    return Object.getOwnPropertyNames(obj).length === 0;
};
console.clear();
console.log('-----');
console.log(isEmpty(''));           // true
console.log(isEmpty(33));           // true
console.log(isEmpty([]));           // true
console.log(isEmpty({}));           // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello'));      // true
console.log(isEmpty([1, 2, 3]));    // true
console.log(isEmpty({ test: 1 }));  // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date()));   // true
console.log(isEmpty(Infinity));     // true
console.log(isEmpty(null));         // true
console.log(isEmpty(undefined));    // true
 8
Author: GibboK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-20 12:38:56

Si jQuery y el navegador web no están disponibles, también hay una función isEmpty en el guion bajo.js.

_.isEmpty({}) // returns true

Además, no asume que el parámetro de entrada sea un objeto. Para una lista o cadena o indefinido, también girará la respuesta correcta.

 7
Author: jichi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-14 03:02:57

Mi opinión:

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

var a = {a:1, b:2}
var b = {}

console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true

Simplemente, no creo que todos los navegadores implementen Object.keys() actualmente.

 6
Author: NiKo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-31 13:39:19

Un bucle simple:

var is_empty = true;
for(var i in obj) {
    is_empty = false;
    break;
}
 5
Author: Vad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-10 10:32:10

Además de la respuesta de los Vs:

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

Es jquery + jquery.json

 3
Author: starikovs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-26 12:33:27

Advertencia! Cuidado con las limitaciones de JSON.

javascript:
  obj={  f:function(){}  };
  alert( "Beware!! obj is NOT empty!\n\nobj = {  f:function(){}  }" + 
               "\n\nJSON.stringify( obj )\n\nreturns\n\n" +
                        JSON.stringify( obj ) );

Muestra

    Beware!! obj is NOT empty!

    obj = {  f:function(){}  }

    JSON.stringify( obj )

    returns

    {}
 3
Author: Ekim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-24 01:52:50

Azúcar.JS proporciona objetos extendidos para este propósito. El código es limpio y simple:

Hacer un objeto extendido:

a = Object.extended({})

Compruebe su tamaño:

a.size()
 3
Author: mikemaccana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-16 09:46:12

Otra alternativa es usar is.js (14kB) a diferencia de jquery (32kB), lodash (50kB), o underscore (16.4 kB). ser.js demostró ser la biblioteca más rápida entre las bibliotecas antes mencionadas que podrían usarse para determinar si un objeto está vacío.

Http://jsperf.com/check-empty-object-using-libraries

Obviamente, todas estas bibliotecas no son exactamente las mismas, por lo que si necesita manipular fácilmente el DOM, entonces jquerytodavía podría ser una buena opción o si necesita algo más que comprobar el tipo, entonces lodasho underscore podría ser bueno. En cuanto a es.js, aquí está la sintaxis:

var a = {};
is.empty(a); // true
is.empty({"hello": "world"}) // false

Al igual que el subrayado y el lodash _.isObject(), esto no es exclusivamente para objects sino que también se aplica a arrays y strings.

Bajo el capó esta biblioteca está usando Object.getOwnPropertyNames que es similar a Object.keys pero Object.getOwnPropertyNames es más completo ya que devolverá enumerable y no enumerable propiedades como se describe aquí.

is.empty = function(value) {
    if(is.object(value)){
        var num = Object.getOwnPropertyNames(value).length;
        if(num === 0 || (num === 1 && is.array(value)) || (num === 2 && is.arguments(value))){
            return true;
        }
        return false;
    } else {
        return value === '';
    }
};

Si no desea traer una biblioteca (lo cual es comprensible) y sabe que solo está verificando objetos (no matrices o cadenas), entonces la siguiente función debería satisfacer sus necesidades.

function isEmptyObject( obj ) {
    return Object.getOwnPropertyNames(obj).length === 0;
}

Esto es solo un poco más rápido de lo que es.js aunque solo porque no está comprobando si es un objeto.

 3
Author: cwadding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:27

La respuesta correcta es:

const isEmptyObject = obj =>
  Object.getOwnPropertyNames(obj).length === 0 &&
  Object.getOwnPropertySymbols(obj).length === 0 &&
  Object.getPrototypeOf(obj) === Object.prototype;

Esto comprueba que:

  • El objeto no tiene propiedades propias (independientemente de su enumerabilidad).
  • El objeto no tiene símbolos de propiedad propios.
  • El prototipo del objeto es exactamente Object.prototype.

En otras palabras, el objeto es indistinguible de uno creado con {}.

 3
Author: Jesse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-05 01:27:38

Me gustaría comprobar si tiene al menos una clave. Eso bastaría para decirme que no está vacía.

Boolean(Object.keys(obj)[0])
 3
Author: Tudor Morar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-11 10:35:16