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

8

Assume 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 of knowing the "size" of the object, that is, how many "other objects" are inside it?

    
asked by anonymous 07.05.2014 / 16:56

1 answer

6

One solution I found was to use the Object.keys() function 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 through the object:

var tamanho= 0;  
for (var i in vendas) {
    if (vendas.hasOwnProperty(i)) {
        tamanho++;
    }
}
    
07.05.2014 / 16:56