How to know the "size" (amount of properties/attributes) of an object in Javascript?

Asked

Viewed 8,713 times

8

Suppose an object as follows:

vendas = {
    obs1:{
        Venda1:{Regiao:"Norte", Valor: 200}, 
        Venda2:{Regiao:"Sul", Valor:100}
    }, 
    obs2:{
        Venda1:{Regiao:"Norte", Valor: 50}, 
        Venda2:{Regiao:"Sul", Valor:20}
    }
}

What are the ways to know the "size" of the object, that is, how many "other objects" are inside it?

  • 1

    By "size" do you mean the number of bytes the object occupies in memory or the amount of attributes? It might be nice to edit the question to make it clearer. : ) (I ask this because I understood in your answer that the return with Object.keys is 2)

  • 1

    @Luizvieira Number of attributes, really not clear! I edited to try to improve.

1 answer

10


One solution I found was to use the function Object.keys() together with length:

Object.keys(vendas).length //2, isto é Obs1 e Obs2

Object.keys(vendas.obs1).length //2, isto é, Venda1 e Venda2

In older browsers you may need to loop the object:

var tamanho= 0;  
for (var i in vendas) {
    if (vendas.hasOwnProperty(i)) {
        tamanho++;
    }
}
  • 1

    That. The other solution (by the way, the only one in old implementations like IE8) is to loop for..in on the properties and count them "in the nail".

  • @bfavaretto added this solution as well

Browser other questions tagged

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