Cómo hacer coincidir un diccionario vacío en Javascript?


Desde el nodo REPL cosa,

> d = {}
{}
> d === {}
false
> d == {}
false

Dado que tengo un diccionario vacío, ¿cómo me aseguro de que sea un diccionario vacío ?

Author: Bill the Lizard, 2011-05-20

10 answers

function isEmpty(obj) {
  return Object.keys(obj).length === 0;
}
 58
Author: Raynos,
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-20 13:35:24

Puede extender Object.prototype con este método isEmpty para verificar si un objeto no tiene propiedades propias:

Object.prototype.isEmpty = function() {
    for (var prop in this) if (this.hasOwnProperty(prop)) return false;
    return true;
};
 19
Author: Gumbo,
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-20 13:54:07

¿Qué tal usar jQuery?

$.isEmptyObject(d)
 12
Author: stroz,
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-02-10 19:58:20

Dado que no tiene atributos, un bucle for no tendrá nada que iterar. Para dar crédito donde se debe, encontré esta sugerencia aquí .

function isEmpty(ob){
   for(var i in ob){ return false;}
  return true;
}

isEmpty({a:1}) // false
isEmpty({}) // true
 10
Author: David Ruttka,
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-20 13:32:51

Esto es lo que usa jQuery, funciona bien. Aunque esto requiere que el script jQuery use isEmptyObject .

isEmptyObject: function( obj ) {
    for ( var name in obj ) {
        return false;
    }
    return true;
}

//Example
var temp = {};
$.isEmptyObject(temp); // returns True
temp ['a'] = 'some data';
$.isEmptyObject(temp); // returns False

Si incluir jQuery no es una opción, simplemente cree una función javascript pura separada.

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

//Example
var temp = {};
isEmptyObject(temp); // returns True
temp ['b'] = 'some data';
isEmptyObject(temp); // returns False
 8
Author: cevaris,
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-05 14:27:58

Estoy lejos de ser un erudito de JavaScript, pero ¿funciona lo siguiente?

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

Tiene la ventaja de ser una llamada a una función pura de una línea.

 2
Author: Steve Bennett,
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-27 13:27:50

Tendrías que comprobar que era de tipo 'object' así:

(typeof(d) === 'object')

Y luego implementar una función de 'tamaño' corto para comprobar que está vacío, como se menciona aquí.

 1
Author: chrisf,
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
var SomeDictionary = {};
if(jQuery.isEmptyObject(SomeDictionary))
// Write some code for dictionary is empty condition
else
// Write some code for dictionary not empty condition

Esto Funciona bien.

 1
Author: VAMSHI PAIDIMARRI,
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-12-23 11:24:04

Si intenta esto en el nodo.js usa este fragmento, basado en este código aquí

Object.defineProperty(Object.prototype, "isEmpty", {
    enumerable: false,
    value: function() {
            for (var prop in this) if (this.hasOwnProperty(prop)) return false;
            return true;
        }
    }
);
 0
Author: arbyter,
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-10-27 05:54:32

Si el rendimiento no es una consideración, este es un método simple que es fácil de recordar:

JSON.stringify(obj) === '{}'

Obviamente no quieres estar stringifying objetos grandes en un bucle, sin embargo.

 0
Author: Steve Bennett,
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-01-05 23:49:32