In Javascript, how to check that an object is empty (without jQuery)?

10

By jQuery , I can tell if a Object is empty as follows:

$.isEmptyObject({}); // true
$.isEmptyObject(window); // false

To know if a array is empty, we can do the same thing, but without jQuery it would look like this:

 var arr = []
 arr.length == 0; // True

But what about Object ? How can I find out if it is empty?

I figured I could do this:

Object.keys(obj).length == 0;

But I thought it was not very suitable.

What other possible ways to do this?

Note : I would like the answer to be without the use of jQuery and others, but only using pure javascript.

    
asked by anonymous 31.08.2015 / 22:20

4 answers

9

You can use this function:

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

    return true;
}

It loops in the properties of the object and uses the hasOwnProperty method to check the properties of the object, hasOwnProperty is required if a prototype of an object is passed.

See more at: link

Another way, with ECMAScript 5 support, can be used like this:

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}
    
31.08.2015 / 22:24
4

One way to make this operation quick is to also use the toSource method.

See:

var vazio = {}

var naoVazio = {ola: 'mundo'}

function isEmptyObject(obj)
{
    return obj.toSource() === "({})";

}


isEmptyObject(vazio); // true
isEmptyObject(naoVazio); // false

This is because toSource returns this string that is compared to the function when we call it on an empty object.

See:

({}).toSource(); // "({})"

Important note :

  

Object.prototype.toSource () is non-standard and not supported in IE:

We can see that we would have trouble using this method in the blessed Internet Explorer !

    
31.08.2015 / 22:36
3

For modern sailors: JSON.stringify

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

Example 2:

Assuming that empty is "that has no properties":

var hasOwnProperty = Object.prototype.hasOwnProperty;

function isEmpty(obj) {

    // null é "empty"
    if (obj == null) return true;

    // Suponhamos que se tenha uma propriedade length com um valor diferente de zero
    // Essa proriedade será verdadeira
    if (obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    // Caso contrário ela tem todas as sua propriedades?
    // Isto não se manipula
    // toString e valueOf são erros de enumeração no IE < 9
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }

    return true;
}
  

HOW TO USE?

isEmpty(""), // true
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true

isEmpty("OLÁ!"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false
    
31.08.2015 / 22:47
3

Following the same logic of implementing jquery in version v1.11.3 you can check if it is empty like this:

var objetoVazio = {};
var objetoContemValor = {
  "key": "valor"
};

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

console.log(isEmptyObject(objetoVazio) + ' objeto vazio');
console.log(isEmptyObject(objetoContemValor) + ' objeto com valor');

If necessary, we can decrease the size of for to just one line:

function isEmptyObject(obj) {
    var name;

    for (name in obj) return false;

    return true;
}
    
31.08.2015 / 22:30