15

I currently have a Javascript object that looks like this:

Object {0: 8, 1: 9, 2: 10}

I am trying to get the number of individual items in the object (i.e. 3) but can't figure out how to do so. Since the object isn't an array, I can't just call .length(). I tried huntsList[2].toString().split('.').length to split the items at the commas and count them in this way but it returns 1, since it converts the entire object to a single string that looks like this: ["[object Object]"].

Any suggestions for how I can accomplish this are appreciated.

StephenA
  • 61
  • 6
user3802348
  • 2,502
  • 11
  • 36
  • 49
  • Possible duplicate of [javascript how to find number of children in an object](http://stackoverflow.com/questions/7081165/javascript-how-to-find-number-of-children-in-an-object) – Shady Atef May 30 '16 at 04:03
  • Possible duplicate of [How to get object length](https://stackoverflow.com/questions/5533192/how-to-get-object-length) – Mišo Nov 29 '18 at 13:42

4 Answers4

15

You could get the keys using Object.keys, which returns an array of the keys:

Example

var obj = {0: 8, 1: 9, 2: 10};

var keys = Object.keys(obj);

var len = keys.length
omarjmh
  • 13,632
  • 6
  • 34
  • 42
7

You can use Object.keys(). It returns an array of the keys of an object.

var myObject = {0: 8, 1: 9, 2: 10};
console.log(Object.keys(myObject).length)
dork
  • 4,396
  • 2
  • 28
  • 56
5

1: ES5.1 solution use Object.keys - returns an array of a given object's own enumerable properties

var obj = {
  0: 8,
  1: 9,
  2: 10
}
console.log(Object.keys(obj).length)

2: Pre-ES5 Solution: use for..in and hasOwn

var obj = {
  0: 8,
  1: 9,
  2: 10
};

var propsLength = 0;
for (prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    propsLength = propsLength + 1;
  }
}
console.log(propsLength);

3: Library Solution: Use lodash/underscore Convert it to an array, and query its length, if you need a pure js solution, we can look into how toArray works.

console.log(_.toArray({
  0: 8,
  1: 9,
  2: 10
}).length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
TMB
  • 4,683
  • 4
  • 25
  • 44
1
var obj = {0: 8, 1: 9, 2: 10};
alert(Object.keys(obj).length);

with this code, try to alert the length of you object mate.!

sudhakar phad
  • 191
  • 1
  • 3
  • 12