Javascript Get length of list of items in object?
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>
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
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)