Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Get length of list of items in object?

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.

like image 272
user3802348 Avatar asked May 30 '16 03:05

user3802348


People also ask

Do JavaScript objects have a length property?

The length property is used to get the number of keys present in the object. It gives the length of the object. the length of the object.

How do you find the number of elements in an object?

To get the number of elements in a JavaScript object, we can use the Object. keys method. const count = Object. keys(obj).

How do you determine the size of an object?

One way to get an estimate of an object's size in Java is to use getObjectSize(Object) method of the Instrumentation interface introduced in Java 5. As we could see in Javadoc documentation, the method provides “implementation-specific approximation” of the specified object's size.

How do you find the length of a object in TypeScript?

To get the length of an object in TypeScript:Use the Object. keys() method to get an array of the object's keys. Access the length property on the array of keys. The length property will return the number of key-value pairs in the object.


1 Answers

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
like image 149
omarjmh Avatar answered Sep 30 '22 16:09

omarjmh