¿Cómo puedo comprobar si un JSON está vacío en NodeJS?


Tengo una función que comprueba si una solicitud tiene o no consultas, y realiza diferentes acciones basadas en eso. Actualmente, tengo if(query) hacer esto otra cosa otra cosa. Sin embargo, parece que cuando no hay datos de consulta, termino con un objeto JSON {}. Como tal, necesito reemplazar if(query) con if(query.isEmpty()) o algo por el estilo. ¿Alguien puede explicar cómo pude hacer esto en NodeJS? ¿El objeto JSON V8 tiene alguna funcionalidad de este tipo?

Author: Drise, 2012-07-14

5 answers

Puede usar cualquiera de estas funciones:

// This should work in node.js and other ES5 compliant implementations.
function isEmptyObject(obj) {
  return !Object.keys(obj).length;
}

// This should work both there and elsewhere.
function isEmptyObject(obj) {
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}

Ejemplo de uso:

if (isEmptyObject(query)) {
  // There are no queries.
} else {
  // There is at least one query,
  // or at least the query object is not empty.
}
 69
Author: PleaseStand,
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-07-14 03:50:29

Puedes usar esto:

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

O esto:

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

También puedes usar esto:

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

  return true;
}

Si usas underscore o jQuery, puedes usar sus llamadas isEmpty o isEmptyObject.

 23
Author: ali haider,
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-10-14 07:57:41

Si tiene compatibilidad con Object.keys, y node tiene compatibilidad, debe usar eso con seguridad.

Sin embargo, si no tiene compatibilidad, y por cualquier razón usar una función de bucle está fuera de cuestión, como yo, usé la siguiente solución:

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

Considere esta solución un uso de 'último recurso' solo si es necesario.

Ver en los comentarios "hay muchas maneras en que esta solución no es ideal".

Tuve un escenario de último recurso, y funcionó perfectamente.

 2
Author: guy mograbi,
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-05-18 23:30:27
Object.keys(myObj).length === 0;

Como es necesario simplemente comprobar si el objeto está vacío, será mejor llamar directamente a un objeto de método nativo.llaves (myObj).length que devuelve la matriz de claves iterando internamente con for..in loop.As Object.hasOwnProperty devuelve un resultado booleano basado en la propiedad presente en un objeto que itera con for..in bucle y tendrá complejidad de tiempo O (N2).

Por otro lado, llamar a un UDF que a su vez tiene por encima de dos implementaciones u otras funcionará bien para objetos pequeños pero bloqueará el código que tendrá un impacto severo en la perormancia general si el tamaño del objeto es grande a menos que nada más esté esperando en el bucle de eventos.

 1
Author: Shubham Sharma,
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-13 08:55:12

Mi solución:

let isEmpty = (val) => {
    let typeOfVal = typeof val;
    switch(typeOfVal){
        case 'object':
            return (val.length == 0) || !Object.keys(val).length;
            break;
        case 'string':
            let str = val.trim();
            return str == '' || str == undefined;
            break;
        case 'number':
            return val == '';
            break;
        default:
            return val == '' || val == undefined;
    }
};
console.log(isEmpty([1,2,4,5])); // false
console.log(isEmpty({id: 1, name: "Trung",age: 29})); // false
console.log(isEmpty('TrunvNV')); // false
console.log(isEmpty(8)); // false
console.log(isEmpty('')); // true
console.log(isEmpty('   ')); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
 0
Author: Trung Nguyên,
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-12 08:52:10