I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
44 Answers 44
Updated answer
Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys()
so the above code just becomes:
var size = Object.keys(myObj).length;
This doesn't have to modify any existing prototype since Object.keys()
is now built-in.
Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.
Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites.
Object.keys
or Object.getOwnPropertyNames
does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols
.
var person = {
[Symbol('name')]: 'John Doe',
[Symbol('age')]: 33,
"occupation": "Programmer"
};
const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1
let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2
Older answer
The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:
Object.size = function(obj) {
var size = 0,
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
const myObj = {}
var size = Object.size(myObj);
There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.
-
68@Tres - your code can be broken if someone would come and overide the 'size' property without knowing you declared it already somewhere in the code, so it's always worth checking if it's already definedvsync– vsync06/14/2011 11:30:19Commented Jun 14, 2011 at 11:30
-
19@vsync You are very correct. One should always implement necessary sanity checks :)Tres– Tres06/24/2011 02:03:57Commented Jun 24, 2011 at 2:03
-
161Why is everyone ignoring this:
Object.keys(obj).length
Muhammad Umer– Muhammad Umer02/25/2015 00:14:15Commented Feb 25, 2015 at 0:14 -
37@MuhammadUmer Probably because that method didn't even exist when this answer was written. Even today, using it will probably require a polyfill for old browsers.Chris Hayes– Chris Hayes05/09/2015 01:53:56Commented May 9, 2015 at 1:53
-
26@stonyau IE8, IE9, IE10 are dead browsers that don't get support from Microsoft. IE8, IE9, IE10 user gets notification from Microsoft, that they use old, unsupported browser and should expect that stuff will not work for them. support.microsoft.com/en-us/kb/3123303Lukas Liesis– Lukas Liesis01/19/2016 09:08:39Commented Jan 19, 2016 at 9:08
If you know you don't have to worry about hasOwnProperty
checks, you can use the Object.keys() method in this way:
Object.keys(myArray).length
-
26why not? from what I know, it is a standard: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…vsync– vsync06/06/2011 11:51:43Commented Jun 6, 2011 at 11:51
-
109It's not a universally implemented method, but you can check which browser supports it with this table.aeosynth– aeosynth06/06/2011 19:08:53Commented Jun 6, 2011 at 19:08
-
27time to switch to firefox = unfortunately, you switching doesn't mean your website's users will...mdup– mdup08/13/2012 11:25:15Commented Aug 13, 2012 at 11:25
-
87@ripper234 no IE support = time to polyfillJohn Dvorak– John Dvorak12/13/2012 06:27:43Commented Dec 13, 2012 at 6:27
-
24@ripper234 who cares about IE, no one should care about IE unstandards, only standards. users wanna use IE then they will not navigate my website I do not care any more. developers should not polyfill not standards made by ie "developers"albanx– albanx03/21/2014 15:17:03Commented Mar 21, 2014 at 15:17
Updated: If you're using Underscore.js (recommended, it's lightweight!), then you can just do
_.size({one : 1, two : 2, three : 3});
=> 3
If not, and you don't want to mess around with Object properties for whatever reason, and are already using jQuery, a plugin is equally accessible:
$.assocArraySize = function(obj) {
// http://stackoverflow.com/a/6700/11236
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
-
8
_.size()
was the perfect solution for my Meteor project, which has underscore.js support.tokyovariable– tokyovariable08/01/2013 17:05:55Commented Aug 1, 2013 at 17:05 -
4I use underscore and this post just reminded me that I'm not using it enough in this project. If you handle objects, you should have underscore.js available.jbolanos– jbolanos11/20/2013 20:51:38Commented Nov 20, 2013 at 20:51
-
3
-
underscorejs, things that should be under js :)anwar– anwar10/30/2015 10:02:47Commented Oct 30, 2015 at 10:02
-
1@Babydead to distinguish real properties of the object vs inherited ones. developer.mozilla.org/en/docs/Web/JavaScript/Reference/…ripper234– ripper23402/12/2017 19:56:20Commented Feb 12, 2017 at 19:56
Here's the most cross-browser solution.
This is better than the accepted answer because it uses native Object.keys if exists. Thus, it is the fastest for all modern browsers.
if (!Object.keys) {
Object.keys = function (obj) {
var arr = [],
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(key);
}
}
return arr;
};
}
Object.keys(obj).length;
-
8
Object.keys()
returns an array that contains the names of only those properties that are enumerable. If you want an array with ALL properties, you should useObject.getOwnPropertyNames()
instead. See developer.mozilla.org/en/docs/Web/JavaScript/Reference/…John Slegers– John Slegers03/07/2016 12:40:48Commented Mar 7, 2016 at 12:40
Simply use this to get the length
:
Object.keys(myObject).length
-
13please explain how your answer differs from stackoverflow.com/a/6700/8632727Patata– Patata02/13/2018 13:04:28Commented Feb 13, 2018 at 13:04
-
1Good, it's always better to name your variables according to what they actually are. Makes your code more readable to other devs.Barry Michael Doyle– Barry Michael Doyle04/04/2018 08:26:47Commented Apr 4, 2018 at 8:26
-
6Before the "myArray" -> "myObject" edit, this was identical to the second-highest upvoted answer.Yunnosch– Yunnosch05/25/2018 06:44:27Commented May 25, 2018 at 6:44
-
5Same as past responses.Alberto Perez– Alberto Perez08/27/2019 09:47:02Commented Aug 27, 2019 at 9:47
-
Same as the linked answer, but without any explanation.Zsolt Meszaros– Zsolt Meszaros08/26/2023 15:32:02Commented Aug 26, 2023 at 15:32
I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't have a length method:
var element_count = 0;
for (e in myArray) { if (myArray.hasOwnProperty(e)) element_count++; }
@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".
-
9Will not work, because it will count methods too, that are added through prototype.Lajos Mészáros– Lajos Mészáros10/08/2013 11:32:57Commented Oct 8, 2013 at 11:32
This method gets all your object's property names in an array, so you can get the length of that array which is equal to your object's keys' length.
Object.getOwnPropertyNames({"hi":"Hi","msg":"Message"}).length; // => 2
-
1@PatrickRoberts keys method doesn't return properties from prototype chain. So why the need for hasOwnProperty here. Also getOwnProperty will return hidden properties, as length is in array etc.Muhammad Umer– Muhammad Umer02/26/2015 16:07:25Commented Feb 26, 2015 at 16:07
To not mess with the prototype or other code, you could build and extend your own object:
function Hash(){
var length=0;
this.add = function(key, val){
if(this[key] == undefined)
{
length++;
}
this[key]=val;
};
this.length = function(){
return length;
};
}
myArray = new Hash();
myArray.add("lastname", "Simpson");
myArray.add("age", 21);
alert(myArray.length()); // will alert 2
If you always use the add method, the length property will be correct. If you're worried that you or others forget about using it, you could add the property counter which the others have posted to the length method, too.
Of course, you could always overwrite the methods. But even if you do, your code would probably fail noticeably, making it easy to debug. ;)
-
I think this is the best solution as it doesn't require looping with 'for' which could be costly if the array is bigEmeka Mbah– Emeka Mbah06/01/2016 19:53:54Commented Jun 1, 2016 at 19:53
We can find the length of Object by using:
const myObject = {};
console.log(Object.values(myObject).length);
-
Theoretically, his would be slower than the "keys" method if you have long values as it is directly accessing the values then counting them.JSG– JSG06/06/2021 21:55:42Commented Jun 6, 2021 at 21:55
Here's how and don't forget to check that the property is not on the prototype chain:
var element_count = 0;
for(var e in myArray)
if(myArray.hasOwnProperty(e))
element_count++;
Here is a completely different solution that will only work in more modern browsers (Internet Explorer 9+, Chrome, Firefox 4+, Opera 11.60+, and Safari 5.1+)
See this jsFiddle.
Setup your associative array class
/**
* @constructor
*/
AssociativeArray = function () {};
// Make the length property work
Object.defineProperty(AssociativeArray.prototype, "length", {
get: function () {
var count = 0;
for (var key in this) {
if (this.hasOwnProperty(key))
count++;
}
return count;
}
});
Now you can use this code as follows...
var a1 = new AssociativeArray();
a1["prop1"] = "test";
a1["prop2"] = 1234;
a1["prop3"] = "something else";
alert("Length of array is " + a1.length);
-
I think that is not safe. For example it cannot have an element with a key of "length", the statement a1["length"] = "Hello world"; fails to store the entry. Also the statement a1["hasOwnProperty"] = "some prop"; totaly breaks the functionPanos Theof– Panos Theof10/26/2014 11:16:54Commented Oct 26, 2014 at 11:16
-
3@PanosTheof I don't think you'd want it to store the value if you used the
length
property, any code that used it would have to ensure it did not try and store againstlength
, but I guess that would be the same if it was a standard array too. OverridinghasOwnProperty
on any object would most likely produce an undesired result.Ally– Ally10/27/2014 00:03:39Commented Oct 27, 2014 at 0:03
If you need an associative data structure that exposes its size, better use a map instead of an object.
const myMap = new Map();
myMap.set("firstname", "Gareth");
myMap.set("lastname", "Simpson");
myMap.set("age", 21);
console.log(myMap.size); // 3
Use Object.keys(myObject).length
to get the length of object/array
var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
console.log(Object.keys(myObject).length); //3
Using the Object.entries
method in order to retrieve the object length is one way of achieving it
const objectLength = obj => Object.entries(obj).length;
const person = {
id: 1,
name: 'John',
age: 30
}
const car = {
type: 2,
color: 'red',
}
console.log(objectLength(person)); // 3
console.log(objectLength(car)); // 2
Use:
var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
obj = Object.keys(myArray).length;
console.log(obj)
<script>
myObj = {"key1" : "Hello", "key2" : "Goodbye"};
var size = Object.keys(myObj).length;
console.log(size);
</script>
<p id="myObj">The number of <b>keys</b> in <b>myObj</b> are: <script>document.write(size)</script></p>
This works for me:
var size = Object.keys(myObj).length;
For some cases it is better to just store the size in a separate variable. Especially, if you're adding to the array by one element in one place and can easily increment the size. It would obviously work much faster if you need to check the size often.
The simplest way is like this:
Object.keys(myobject).length
Where myobject is the object of what you want the length of.
-
4This appears to be just a repeat of this existing answer.Pang– Pang11/15/2018 03:22:04Commented Nov 15, 2018 at 3:22
-
@Pang agreed, and it does not provide any further context like other answers do.Mystical– Mystical01/21/2019 04:23:14Commented Jan 21, 2019 at 4:23
@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".
And in fairness to @palmsey he was quite correct. They aren't associative arrays; they're definitely objects :) - doing the job of an associative array. But as regards to the wider point, you definitely seem to have the right of it according to this rather fine article I found:
JavaScript "Associative Arrays" Considered Harmful
But according to all this, the accepted answer itself is bad practice?
Specify a prototype size() function for Object
If anything else has been added to Object .prototype, then the suggested code will fail:
<script type="text/javascript">
Object.prototype.size = function () {
var len = this.length ? --this.length : -1;
for (var k in this)
len++;
return len;
}
Object.prototype.size2 = function () {
var len = this.length ? --this.length : -1;
for (var k in this)
len++;
return len;
}
var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
alert("age is " + myArray["age"]);
alert("length is " + myArray.size());
</script>
I don't think that answer should be the accepted one as it can't be trusted to work if you have any other code running in the same execution context. To do it in a robust fashion, surely you would need to define the size method within myArray and check for the type of the members as you iterate through them.
If we have the hash
hash = {"a" : "b", "c": "d"};
we can get the length using the length of the keys which is the length of the hash:
keys(hash).length
-
2This is a great answer, however I can't find any documentation for this keys function. So I can't be confident on the cross browser support.chim– chim09/03/2015 09:54:56Commented Sep 3, 2015 at 9:54
-
2Unfortunately, this is not as good an answer as I first thought! It turns out that the keys function is only available in the chrome and firefox web consoles. If you put this code in to a script then it will fail with Uncaught ReferenceError: keys is not definedchim– chim09/03/2015 10:14:33Commented Sep 3, 2015 at 10:14
-
stackoverflow.com/questions/32372685/…chim– chim09/03/2015 10:17:54Commented Sep 3, 2015 at 10:17
-
1How is this different from aeosynth's answer?Peter Mortensen– Peter Mortensen09/17/2016 18:32:40Commented Sep 17, 2016 at 18:32
var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
- Object.values(myObject).length
- Object.entries(myObject).length
- Object.keys(myObject).length
-
1Which one is faster among the above 3.Siluveru Kiran Kumar– Siluveru Kiran Kumar06/21/2019 07:23:22Commented Jun 21, 2019 at 7:23
-
1
-
1how can we say that it Object.values(myObject).length is faster is there any example Thanks, @tdjprogSiluveru Kiran Kumar– Siluveru Kiran Kumar07/02/2019 07:02:20Commented Jul 2, 2019 at 7:02
-
1just try this in console:
var myObject = {}; for (let i=0; i<10000000; i++) myObject[i] = i;
tdjprog– tdjprog07/03/2019 01:25:05Commented Jul 3, 2019 at 1:25 -
1why Object.values(myObject).length faster, where as Object.entries(myObject).length not giving output even after sometime what is the reason here ? Thanks @tdjprogSiluveru Kiran Kumar– Siluveru Kiran Kumar07/03/2019 07:02:17Commented Jul 3, 2019 at 7:02
What about something like this --
function keyValuePairs() {
this.length = 0;
function add(key, value) { this[key] = value; this.length++; }
function remove(key) { if (this.hasOwnProperty(key)) { delete this[key]; this.length--; }}
}
Here are some methods:
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
//first method
console.log(Object.entries(myObject).length); //3
//second method
let len = 0;
for(let i in myObject)len++;
console.log(len); //3
If you are using AngularJS 1.x you can do things the AngularJS way by creating a filter and using the code from any of the other examples such as the following:
// Count the elements in an object
app.filter('lengthOfObject', function() {
return function( obj ) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
}
})
Usage
In your controller:
$scope.filterResult = $filter('lengthOfObject')($scope.object)
Or in your view:
<any ng-expression="object | lengthOfObject"></any>
-
4The OP has not asked for a AngularJS version. This is not a valid answer to the question.hodgef– hodgef12/04/2015 21:07:07Commented Dec 4, 2015 at 21:07
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
console.log(Object.keys(myObject).length)
// o/p 3
-
What does "o/p 3" mean?Peter Mortensen– Peter Mortensen07/10/2020 18:43:17Commented Jul 10, 2020 at 18:43
-
An explanation of this answer would be in order.Peter Mortensen– Peter Mortensen07/10/2020 18:43:49Commented Jul 10, 2020 at 18:43
-
2Also, how is it different from previous answers, e.g. shaheb's answer?Peter Mortensen– Peter Mortensen07/10/2020 18:45:23Commented Jul 10, 2020 at 18:45
-
@PeterMortensen "o/p" probably means "output".Sebastian Simon– Sebastian Simon03/15/2021 10:07:04Commented Mar 15, 2021 at 10:07
-
A variation on some of the above is:
var objLength = function(obj){
var key,len=0;
for(key in obj){
len += Number( obj.hasOwnProperty(key) );
}
return len;
};
It is a bit more elegant way to integrate hasOwnProp.
If you don't care about supporting Internet Explorer 8 or lower, you can easily get the number of properties in an object by applying the following two steps:
- Run either
Object.keys()
to get an array that contains the names of only those properties that are enumerable orObject.getOwnPropertyNames()
if you want to also include the names of properties that are not enumerable. - Get the
.length
property of that array.
If you need to do this more than once, you could wrap this logic in a function:
function size(obj, enumerablesOnly) {
return enumerablesOnly === false ?
Object.getOwnPropertyNames(obj).length :
Object.keys(obj).length;
}
How to use this particular function:
var myObj = Object.create({}, {
getFoo: {},
setFoo: {}
});
myObj.Foo = 12;
var myArr = [1,2,5,4,8,15];
console.log(size(myObj)); // Output : 1
console.log(size(myObj, true)); // Output : 1
console.log(size(myObj, false)); // Output : 3
console.log(size(myArr)); // Output : 6
console.log(size(myArr, true)); // Output : 6
console.log(size(myArr, false)); // Output : 7
See also this Fiddle for a demo.
Here's a different version of James Cogan's answer. Instead of passing an argument, just prototype out the Object class and make the code cleaner.
Object.prototype.size = function () {
var size = 0,
key;
for (key in this) {
if (this.hasOwnProperty(key)) size++;
}
return size;
};
var x = {
one: 1,
two: 2,
three: 3
};
x.size() === 3;
jsfiddle example: http://jsfiddle.net/qar4j/1/
-
6
Object.prototype
- bad idea.Dziad Borowy– Dziad Borowy10/14/2013 10:50:14Commented Oct 14, 2013 at 10:50 -
@tborychowski can you please explain why?Mohamad– Mohamad03/05/2014 13:09:41Commented Mar 5, 2014 at 13:09
-
here's one article: bit.ly/1droWrG. I'm not saying it mustn't be done, only that you need to know all the repercussions before you do this.Dziad Borowy– Dziad Borowy03/05/2014 15:55:08Commented Mar 5, 2014 at 15:55
-
If you’re going to extend built-in prototypes or polyfill a property (i.e. monkey-patch), please do it correctly: for forward compatibility, check if the property exists first, then make the property non-enumerable so that the own keys of constructed objects aren’t polluted. For methods use actual methods. My recommendation: follow these examples which demonstrate how to add a method that behaves as closely as possible like built-in methods.Sebastian Simon– Sebastian Simon05/09/2020 09:43:15Commented May 9, 2020 at 9:43
You can always do Object.getOwnPropertyNames(myObject).length
to get the same result as [].length
would give for normal array.
-
1
Object.keys()
returns an array that contains the names of only those properties that are enumerable. If you want an array with ALL properties, you should useObject.getOwnPropertyNames()
instead. See developer.mozilla.org/en/docs/Web/JavaScript/Reference/…John Slegers– John Slegers03/07/2016 12:39:44Commented Mar 7, 2016 at 12:39 -
3How is this different from aeosynth's answer?Peter Mortensen– Peter Mortensen09/17/2016 18:35:14Commented Sep 17, 2016 at 18:35
You can simply use Object.keys(obj).length
on any object to get its length. Object.keys returns an array containing all of the object keys (properties) which can come in handy for finding the length of that object using the length of the corresponding array. You can even write a function for this. Let's get creative and write a method for it as well (along with a more convienient getter property):
function objLength(obj)
{
return Object.keys(obj).length;
}
console.log(objLength({a:1, b:"summit", c:"nonsense"}));
// Works perfectly fine
var obj = new Object();
obj['fish'] = 30;
obj['nullified content'] = null;
console.log(objLength(obj));
// It also works your way, which is creating it using the Object constructor
Object.prototype.getLength = function() {
return Object.keys(this).length;
}
console.log(obj.getLength());
// You can also write it as a method, which is more efficient as done so above
Object.defineProperty(Object.prototype, "length", {get:function(){
return Object.keys(this).length;
}});
console.log(obj.length);
// probably the most effictive approach is done so and demonstrated above which sets a getter property called "length" for objects which returns the equivalent value of getLength(this) or this.getLength()
-
4How is this different from aeosynth's answer?Peter Mortensen– Peter Mortensen09/17/2016 18:39:02Commented Sep 17, 2016 at 18:39
-
It's because it shows how to make it as a function and a global object method (more object oriented and uses some form of encapsulation); however aeosynth's answer doesn't.Mystical– Mystical09/18/2016 01:34:25Commented Sep 18, 2016 at 1:34
-
If you’re going to extend built-in prototypes or polyfill a property (i.e. monkey-patch), please do it correctly: for forward compatibility, check if the property exists first, then make the property non-enumerable so that the own keys of constructed objects aren’t polluted. For methods use actual methods. My recommendation: follow these examples which demonstrate how to add a method that behaves as closely as possible like built-in methods.Sebastian Simon– Sebastian Simon05/09/2020 09:45:37Commented May 9, 2020 at 9:45
-
Also, how is writing a method "more efficient"?Sebastian Simon– Sebastian Simon05/09/2020 09:46:00Commented May 9, 2020 at 9:46
Explore related questions
See similar questions with these tags.
Object.
{keys
,values
,entries
}(obj).length
have now been mentioned a total of 38 times in 16 answers plus in the comments of this question, and another 11 times in 7 deleted answers. I think that’s enough now.