-2

Below is my object in JavaScript, how can i calculate the length of it.

var treeObj = {
            1: ['96636736','10'],
            2 : ['96636734','20'],
            3 : ['96636731','45']
              };    

treeObj .length is not working. any help would be appreciated. Thanks.

opensource-developer
  • 2,826
  • 4
  • 38
  • 88

2 Answers2

2

You can do this:

Object.getOwnPropertyNames(treeObj).length;  // 3

getOwnPropertyNames returns array of properties of treeObj whose length can be checked.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • It should be noted that you should avoid this method if you are targeting older browsers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames – JLRishe May 29 '14 at 05:55
1

To count the number of properties an object has, you need to loop through the properties but remember to use the hasOwnProperty function:

var count = 0;
for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
        count++;
    }
}

If you forget to do that, you will be looping through inherited properties. If you (or some library) has assigned a function to the prototype of Object, then all objects will seem to have that property, and thus will seem one item "longer" than they intrinsically are.

consider using jQuery's each instead:

var count = 0;
$.each(obj, function(k, v) { count++; });

OR simply,

 for (var p in obj) 
            count++;

UPDATE With current browsers:

Object.keys(someObj).length

Refer Old Post

Community
  • 1
  • 1
  • jQuery's `$.each()` doesn't include a `.hasOwnProperty` check. Not sure how jQuery relates to this question in the first place. – cookie monster May 29 '14 at 05:07
  • Nope, of course `$.each` doesn't include a `.hasOwnProperty` is a just another example to get the count. –  May 29 '14 at 05:11
  • *"To avoid the need to remember this..."* sounded like you're suggesting that it does. If not, then he might as well do `for (var p in obj) count++;` since it's shorter and faster. – cookie monster May 29 '14 at 05:14
  • yeah, it is. Let me edit the answer. Thanks –  May 29 '14 at 05:17