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

Asked

Viewed 51,834 times

16

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

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

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

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

However, and the Object? How can I know if it is empty?

I figured I could do it like this:

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

But I didn’t think it was appropriate.

What are other possible ways to do this?

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

  • 2

    jQuery source: isEmptyObject:Function(a){var b;for(b in a)Return! 1;Return! 0}

  • I bet you gave a $.isEmptyObject.toSource() :)

  • Opened with same editor :)

  • why not use typeof ? and check if it is Undefined

  • typeof will not serve. He returns would "object" for all cases (for empty and non-empty)

5 answers

18


You can use this function:

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

    return true;
}

It loops the properties of the object and uses the method hasOwnProperty to verify the properties of the object, the hasOwnProperty it is necessary if a prototype of an object is passed.

See more in: https://msdn.microsoft.com/pt-br/library/328kyd6z(v=vs.94). aspx

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

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}
  • Note that, as epx said, in jQuery there is no .hasOwnProperty(), so the results may vary.

  • hasOwnProperty() is really necessary?

  • Really, if you get into for is that there is something to iterate. No need to hasOwnProperty.

  • Without the use of hasOwnProperty, if you use prototype, won’t work.

  • In fact hasOwnProperty() would be nice to have if by chance another code added convenience methods, or attributes, directly in Object.prototype, such additions are listed by for.. in, and even an object {} would no longer be considered empty. Filter by hasOwnProperty() returns that {} is empty even with manipulations in Object.prototype.

  • @Henriquedpereira, the last form already has in the question :)

  • Now that I’ve seen it, but you can use it that way too, there’s nothing wrong.

Show 2 more comments

8

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

Behold:

var vazio = {}

var naoVazio = {ola: 'mundo'}

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

}


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

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

Behold:

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

Important remark:

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

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

Updating

As noted by MDN, this method has been depreciated [free translation]:

This feature is no longer recommended. Although some browsers may still support it, it may have already been removed from the relevant web standards, may be in the process of deletion or may be maintained only for compatibility purposes. Avoid using it and update existing code if possible;


Alternatives

Alternatively, you can use Object.keys or Object.values in an Object. These functions will return a Array. You can check the property length.

Behold:


 function isEmptyObject(obj)
 {
    return !!Object.values(obj).length;    
 }
    

or:


 function isEmptyObject(obj)
 {
    return !!Object.keys(obj).length;    
 }
    
  • I like this one :)

  • I found it simpler. And if you need to do this just once, you don’t even need to create a function :)

  • There is an important information to search and ask the question :)

  • Batter!.........................

  • 1

    Does it currently work? I tested it on Chrome, Firefox and Safari and received errors similar to TypeError: b.toSource is not a function. I would review the need to keep this answer...

6

Following the same logic of the implementation of jquery in the version v1.11.3 you can check if it’s 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 the for for only one line:

function isEmptyObject(obj) {
    var name;

    for (name in obj) return false;

    return true;
}
  • I got lost in this detail when I stopped to research on my project how I did this check, it was the same way said in your question, I will reissue with an alternative answer.

  • 1

    I added a suggestion from one line in his for. Got massive!

5

For modern shippers: JSON.stringify

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

2nd Example:

Assuming emptiness 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

3

ECMA 7+:

Object.entries(obj).length === 0 && obj.constructor === Object

Browser other questions tagged

You are not signed in. Login or sign up in order to post.