<p>I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?</p>
<pre><code>const myObject = new Object();
myObject[&quot;firstname&quot;] = &quot;Gareth&quot;;
myObject[&quot;lastname&quot;] = &quot;Simpson&quot;;
myObject[&quot;age&quot;] = 21;
</code></pre>

[{'answer_id': 5232, 'author': 'jj33', 'author_id': 430, 'author_profile': 'https://Stackoverflow.com/users/430', 'pm_score': 5, 'selected': False, 'text': '<p>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:</p>\n\n<pre><code>var element_count = 0;\nfor (e in myArray) {  if (myArray.hasOwnProperty(e)) element_count++; }\n</code></pre>\n\n<p>@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".</p>\n'}, {'answer_id': 6280, 'author': 'doekman', 'author_id': 56, 'author_profile': 'https://Stackoverflow.com/users/56', 'pm_score': 5, 'selected': False, 'text': "<p>Here's how and don't forget to check that the property is not on the prototype chain:</p>\n\n<pre><code>var element_count = 0;\nfor(var e in myArray)\n    if(myArray.hasOwnProperty(e))\n        element_count++;\n</code></pre>\n"}, {'answer_id': 6444, 'author': 'Polsonby', 'author_id': 137, 'author_profile': 'https://Stackoverflow.com/users/137', 'pm_score': 4, 'selected': False, 'text': '<blockquote>\n<blockquote>\n<p>@palmsey: In fairness to the OP, the JavaScript documentation  actually explicitly refer to using variables of type Object in this manner as &quot;associative arrays&quot;.</p>\n</blockquote>\n</blockquote>\n<p>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:</p>\n<p><em><a href="http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/" rel="nofollow noreferrer">JavaScript “Associative Arrays” Considered Harmful</a></em></p>\n<p>But according to all this, <a href="https://stackoverflow.com/questions/5223/length-of-javascript-associative-array#5234">the accepted answer</a> itself is bad practice?</p>\n<blockquote>\n<blockquote>\n<p>Specify a prototype size() function for Object</p>\n</blockquote>\n</blockquote>\n<p>If anything else has been added to Object .prototype, then the suggested code will fail:</p>\n<pre><code>&lt;script type=&quot;text/javascript&quot;&gt;\nObject.prototype.size = function () {\n  var len = this.length ? --this.length : -1;\n    for (var k in this)\n      len++;\n  return len;\n}\nObject.prototype.size2 = function () {\n  var len = this.length ? --this.length : -1;\n    for (var k in this)\n      len++;\n  return len;\n}\nvar myArray = new Object();\nmyArray[&quot;firstname&quot;] = &quot;Gareth&quot;;\nmyArray[&quot;lastname&quot;] = &quot;Simpson&quot;;\nmyArray[&quot;age&quot;] = 21;\nalert(&quot;age is &quot; + myArray[&quot;age&quot;]);\nalert(&quot;length is &quot; + myArray.size());\n&lt;/script&gt;\n</code></pre>\n<p>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.</p>\n'}, {'answer_id': 6700, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 13, 'selected': True, 'text': '<h2>Updated answer</h2>\n<p><strong>Here\'s an update as of 2016 and <a href="http://kangax.github.io/compat-table/es5/" rel="noreferrer">widespread deployment of ES5</a> and beyond.</strong>  For IE9+ and all other modern ES5+ capable browsers, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer"><code>Object.keys()</code></a> so the above code just becomes:</p>\n<pre><code>var size = Object.keys(myObj).length;\n</code></pre>\n<p>This doesn\'t have to modify any existing prototype since <code>Object.keys()</code> is now built-in.</p>\n<p><strong>Edit</strong>: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.</p>\n<p>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.</p>\n<p><code>Object.keys</code> or <code>Object.getOwnPropertyNames</code> does not work for symbolic properties. To return them you need to use <code>Object.getOwnPropertySymbols</code>.</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var person = {\n  [Symbol(\'name\')]: \'John Doe\',\n  [Symbol(\'age\')]: 33,\n  "occupation": "Programmer"\n};\n\nconst propOwn = Object.getOwnPropertyNames(person);\nconsole.log(propOwn.length); // 1\n\nlet propSymb = Object.getOwnPropertySymbols(person);\nconsole.log(propSymb.length); // 2</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Older answer</h2>\n<p>The most robust answer (i.e. that captures the intent of what you\'re trying to do while causing the fewest bugs) would be:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>Object.size = function(obj) {\n  var size = 0,\n    key;\n  for (key in obj) {\n    if (obj.hasOwnProperty(key)) size++;\n  }\n  return size;\n};\n\n// Get the size of an object\nconst myObj = {}\nvar size = Object.size(myObj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>There\'s a sort of convention in JavaScript that you <a href="https://stackoverflow.com/questions/10757455/object-prototype-is-verboten">don\'t add things to Object.prototype</a>, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.</p>\n<hr />\n'}, {'answer_id': 5527037, 'author': 'aeosynth', 'author_id': 131023, 'author_profile': 'https://Stackoverflow.com/users/131023', 'pm_score': 11, 'selected': False, 'text': '<p>If you know you don\'t have to worry about <code>hasOwnProperty</code> checks, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer">Object.keys()</a> method in this way:</p>\n<pre><code>Object.keys(myArray).length\n</code></pre>\n'}, {'answer_id': 6316862, 'author': 'DanMan', 'author_id': 428241, 'author_profile': 'https://Stackoverflow.com/users/428241', 'pm_score': 5, 'selected': False, 'text': '<p>To not mess with the prototype or other code, you could build and extend your own object:</p>\n\n<pre><code>function Hash(){\n    var length=0;\n    this.add = function(key, val){\n         if(this[key] == undefined)\n         {\n           length++;\n         }\n         this[key]=val;\n    }; \n    this.length = function(){\n        return length;\n    };\n}\n\nmyArray = new Hash();\nmyArray.add("lastname", "Simpson");\nmyArray.add("age", 21);\nalert(myArray.length()); // will alert 2\n</code></pre>\n\n<p>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.</p>\n\n<p>Of course, you could always overwrite the methods. But even if you do, your code would probably fail noticeably, making it easy to debug. ;)</p>\n'}, {'answer_id': 6874074, 'author': 'Jānis Elmeris', 'author_id': 99904, 'author_profile': 'https://Stackoverflow.com/users/99904', 'pm_score': 4, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 7177140, 'author': 'Jerry', 'author_id': 909828, 'author_profile': 'https://Stackoverflow.com/users/909828', 'pm_score': 4, 'selected': False, 'text': '<p>What about something like this --</p>\n\n<pre><code>function keyValuePairs() {\n    this.length = 0;\n    function add(key, value) { this[key] = value; this.length++; }\n    function remove(key) { if (this.hasOwnProperty(key)) { delete this[key]; this.length--; }}\n}\n</code></pre>\n'}, {'answer_id': 8186938, 'author': 'wade harrell', 'author_id': 1054363, 'author_profile': 'https://Stackoverflow.com/users/1054363', 'pm_score': 3, 'selected': False, 'text': '<p>A variation on some of the above is:</p>\n\n<pre><code>var objLength = function(obj){    \n    var key,len=0;\n    for(key in obj){\n        len += Number( obj.hasOwnProperty(key) );\n    }\n    return len;\n};\n</code></pre>\n\n<p>It is a bit more elegant way to integrate hasOwnProp.</p>\n'}, {'answer_id': 11346637, 'author': 'ripper234', 'author_id': 11236, 'author_profile': 'https://Stackoverflow.com/users/11236', 'pm_score': 8, 'selected': False, 'text': '<p><strong>Updated</strong>: If you\'re using <a href="http://underscorejs.org/#size">Underscore.js</a> (recommended, it\'s lightweight!), then you can just do</p>\n\n<pre><code>_.size({one : 1, two : 2, three : 3});\n=&gt; 3\n</code></pre>\n\n<p><strong>If not</strong>, and you don\'t want to mess around with Object properties for whatever reason, and are already using jQuery, a plugin is equally accessible:</p>\n\n<pre><code>$.assocArraySize = function(obj) {\n    // http://stackoverflow.com/a/6700/11236\n    var size = 0, key;\n    for (key in obj) {\n        if (obj.hasOwnProperty(key)) size++;\n    }\n    return size;\n};\n</code></pre>\n'}, {'answer_id': 15207568, 'author': 'Eric Anderson', 'author_id': 120067, 'author_profile': 'https://Stackoverflow.com/users/120067', 'pm_score': 2, 'selected': False, 'text': "<p>Below is a version of James Coglan's answer in CoffeeScript for those who have abandoned straight JavaScript :)</p>\n\n<pre><code>Object.size = (obj) -&gt;\n  size = 0\n  size++ for own key of obj\n  size\n</code></pre>\n"}, {'answer_id': 17332295, 'author': 'Sherzod', 'author_id': 928001, 'author_profile': 'https://Stackoverflow.com/users/928001', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>Object.prototype.size = function () {\n    var size = 0,\n        key;\n    for (key in this) {\n        if (this.hasOwnProperty(key)) size++;\n    }\n    return size;\n};\n\nvar x = {\n    one: 1,\n    two: 2,\n    three: 3\n};\n\nx.size() === 3;\n</code></pre>\n\n<p>jsfiddle example: <a href="http://jsfiddle.net/qar4j/1/" rel="noreferrer">http://jsfiddle.net/qar4j/1/</a></p>\n'}, {'answer_id': 18012581, 'author': 'Ally', 'author_id': 837649, 'author_profile': 'https://Stackoverflow.com/users/837649', 'pm_score': 5, 'selected': False, 'text': '<p>Here is a completely different solution that will only work in more modern browsers (Internet\xa0Explorer\xa09+, Chrome, Firefox 4+, Opera 11.60+, and Safari 5.1+)</p>\n<p>See <a href="http://jsfiddle.net/QHDt7/" rel="noreferrer" title="jsFiddle">this jsFiddle</a>.</p>\n<p>Setup your associative array class</p>\n<pre><code>/**\n * @constructor\n */\nAssociativeArray = function () {};\n\n// Make the length property work\nObject.defineProperty(AssociativeArray.prototype, &quot;length&quot;, {\n    get: function () {\n        var count = 0;\n        for (var key in this) {\n            if (this.hasOwnProperty(key))\n                count++;\n        }\n        return count;\n    }\n});\n</code></pre>\n<p>Now you can use this code as follows...</p>\n<pre><code>var a1 = new AssociativeArray();\na1[&quot;prop1&quot;] = &quot;test&quot;;\na1[&quot;prop2&quot;] = 1234;\na1[&quot;prop3&quot;] = &quot;something else&quot;;\nalert(&quot;Length of array is &quot; + a1.length);\n</code></pre>\n'}, {'answer_id': 18560314, 'author': 'Joon', 'author_id': 692528, 'author_profile': 'https://Stackoverflow.com/users/692528', 'pm_score': 6, 'selected': False, 'text': "<p>Here's the most cross-browser solution.</p>\n\n<p>This is better than the accepted answer because it uses native Object.keys if exists.\nThus, it is the fastest for all modern browsers.</p>\n\n<pre><code>if (!Object.keys) {\n    Object.keys = function (obj) {\n        var arr = [],\n            key;\n        for (key in obj) {\n            if (obj.hasOwnProperty(key)) {\n                arr.push(key);\n            }\n        }\n        return arr;\n    };\n}\n\nObject.keys(obj).length;\n</code></pre>\n"}, {'answer_id': 21656259, 'author': 'abo-elleef', 'author_id': 1846073, 'author_profile': 'https://Stackoverflow.com/users/1846073', 'pm_score': 4, 'selected': False, 'text': '<p>If we have the hash </p>\n\n<blockquote>\n  <p>hash =  {"a" : "b", "c": "d"};</p>\n</blockquote>\n\n<p>we can get the length using the length of the keys which is the length of the hash:</p>\n\n<blockquote>\n  <p>keys(hash).length</p>\n</blockquote>\n'}, {'answer_id': 23571866, 'author': 'Ron Sims II', 'author_id': 1341417, 'author_profile': 'https://Stackoverflow.com/users/1341417', 'pm_score': 2, 'selected': False, 'text': "<p>Like most JavaScript problems, there are many solutions.  You could extend the Object that for better or worse works like many other languages' Dictionary (+ first class citizens). Nothing wrong with that, but another option is to construct a new Object that meets your specific needs. </p>\n\n<pre><code>function uberject(obj){\n    this._count = 0;\n    for(var param in obj){\n        this[param] = obj[param];\n        this._count++;\n    }\n}\n\nuberject.prototype.getLength = function(){\n    return this._count;\n};\n\nvar foo = new uberject({bar:123,baz:456});\nalert(foo.getLength());\n</code></pre>\n"}, {'answer_id': 24510557, 'author': 'venkat7668', 'author_id': 2165104, 'author_profile': 'https://Stackoverflow.com/users/2165104', 'pm_score': 5, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>Object.getOwnPropertyNames({"hi":"Hi","msg":"Message"}).length; // =&gt; 2\n</code></pre>\n'}, {'answer_id': 27805509, 'author': 'Eduardo Cuomo', 'author_id': 717267, 'author_profile': 'https://Stackoverflow.com/users/717267', 'pm_score': 2, 'selected': False, 'text': "<h2>Property</h2>\n<pre><code>Object.defineProperty(Object.prototype, 'length', {\n    get: function () {\n        var size = 0, key;\n        for (key in this)\n            if (this.hasOwnProperty(key))\n                size++;\n        return size;\n    }\n});\n</code></pre>\n<h2>Use</h2>\n<pre><code>var o = {a: 1, b: 2, c: 3};\nalert(o.length); // &lt;-- 3\no['foo'] = 123;\nalert(o.length); // &lt;-- 4\n</code></pre>\n"}, {'answer_id': 29579046, 'author': 'stylesenberg', 'author_id': 4132915, 'author_profile': 'https://Stackoverflow.com/users/4132915', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Simple solution:</strong></p>\n\n<pre><code>  var myObject = {};      // ... your object goes here.\n\n  var length = 0;\n\n  for (var property in myObject) {\n    if (myObject.hasOwnProperty(property)){\n      length += 1;\n    }\n  };\n\n  console.log(length);    // logs 0 in my example.\n</code></pre>\n'}, {'answer_id': 32593870, 'author': 'pcnate', 'author_id': 3851647, 'author_profile': 'https://Stackoverflow.com/users/3851647', 'pm_score': 4, 'selected': False, 'text': '<p>If you are using <a href="http://en.wikipedia.org/wiki/AngularJS" rel="noreferrer">AngularJS</a> 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:</p>\n\n<pre><code>// Count the elements in an object\napp.filter(\'lengthOfObject\', function() {\n  return function( obj ) {\n    var size = 0, key;\n    for (key in obj) {\n      if (obj.hasOwnProperty(key)) size++;\n    }\n   return size;\n }\n})\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<p>In your controller:</p>\n\n<pre><code>$scope.filterResult = $filter(\'lengthOfObject\')($scope.object)\n</code></pre>\n\n<p>Or in your view:</p>\n\n<pre><code>&lt;any ng-expression="object | lengthOfObject"&gt;&lt;/any&gt;\n</code></pre>\n'}, {'answer_id': 34734220, 'author': 'Pian0_M4n', 'author_id': 2156913, 'author_profile': 'https://Stackoverflow.com/users/2156913', 'pm_score': 3, 'selected': False, 'text': '<p>You can always do <code>Object.getOwnPropertyNames(myObject).length</code> to get the same result as <code>[].length</code> would give for normal array.</p>\n'}, {'answer_id': 35844733, 'author': 'John Slegers', 'author_id': 1946501, 'author_profile': 'https://Stackoverflow.com/users/1946501', 'pm_score': 3, 'selected': False, 'text': '<p>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:</p>\n\n<ol>\n<li>Run either <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="nofollow noreferrer"><strong><code>Object.keys()</code></strong></a> to get an array that contains the names of only those properties that are <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Enumerability_and_ownership_of_properties" rel="nofollow noreferrer"><strong>enumerable</strong></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames" rel="nofollow noreferrer"><strong><code>Object.getOwnPropertyNames()</code></strong></a> if you want to also include the names of properties that are not enumerable.</li>\n<li>Get the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length" rel="nofollow noreferrer"><strong><code>.length</code></strong></a> property of that array.</li>\n</ol>\n\n<hr>\n\n<p>If you need to do this more than once, you could wrap this logic in a function:</p>\n\n<pre><code>function size(obj, enumerablesOnly) {\n    return enumerablesOnly === false ?\n        Object.getOwnPropertyNames(obj).length :\n        Object.keys(obj).length;\n}\n</code></pre>\n\n<p>How to use this particular function:</p>\n\n<pre><code>var myObj = Object.create({}, {\n    getFoo: {},\n    setFoo: {}\n});\nmyObj.Foo = 12;\n\nvar myArr = [1,2,5,4,8,15];\n\nconsole.log(size(myObj));        // Output : 1\nconsole.log(size(myObj, true));  // Output : 1\nconsole.log(size(myObj, false)); // Output : 3\nconsole.log(size(myArr));        // Output : 6\nconsole.log(size(myArr, true));  // Output : 6\nconsole.log(size(myArr, false)); // Output : 7\n</code></pre>\n\n<p>See also <a href="https://jsfiddle.net/0x11tv73/5/" rel="nofollow noreferrer"><strong>this Fiddle</strong></a> for a demo.</p>\n'}, {'answer_id': 37307278, 'author': 'Oriol', 'author_id': 1529630, 'author_profile': 'https://Stackoverflow.com/users/1529630', 'pm_score': 4, 'selected': False, 'text': '<p>If you need an associative data structure that exposes its size, better use a map instead of an object.</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>const myMap = new Map();\n\nmyMap.set("firstname", "Gareth");\nmyMap.set("lastname", "Simpson");\nmyMap.set("age", 21);\n\nconsole.log(myMap.size); // 3</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 37537045, 'author': 'Mahendra Kulkarni', 'author_id': 6011619, 'author_profile': 'https://Stackoverflow.com/users/6011619', 'pm_score': 4, 'selected': False, 'text': '<p>Use:</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var myArray = new Object();\r\nmyArray["firstname"] = "Gareth";\r\nmyArray["lastname"] = "Simpson";\r\nmyArray["age"] = 21;\r\nobj = Object.keys(myArray).length;\r\nconsole.log(obj)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 38816218, 'author': 'christian Nguyen', 'author_id': 4225143, 'author_profile': 'https://Stackoverflow.com/users/4225143', 'pm_score': 0, 'selected': False, 'text': '<p>The solution work for many cases and cross browser:</p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>var getTotal = function(collection) {\n\n    var length = collection[\'length\'];\n    var isArrayObject =  typeof length == \'number\' &amp;&amp; length &gt;= 0 &amp;&amp; length &lt;= Math.pow(2,53) - 1; // Number.MAX_SAFE_INTEGER\n\n    if(isArrayObject) {\n        return collection[\'length\'];\n    }\n\n    i= 0;\n    for(var key in collection) {\n        if (collection.hasOwnProperty(key)) {\n            i++;\n        }\n    }\n\n    return i;\n};\n</code></pre>\n\n<p><strong>Data Examples:</strong></p>\n\n<pre><code>// case 1\nvar a = new Object();\na["firstname"] = "Gareth";\na["lastname"] = "Simpson";\na["age"] = 21;\n\n//case 2\nvar b = [1,2,3];\n\n// case 3\nvar c = {};\nc[0] = 1;\nc.two = 2;\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>getLength(a); // 3\ngetLength(b); // 3\ngetLength(c); // 2\n</code></pre>\n'}, {'answer_id': 39542137, 'author': 'Mystical', 'author_id': 6368005, 'author_profile': 'https://Stackoverflow.com/users/6368005', 'pm_score': 3, 'selected': False, 'text': '<p>You can simply use <code>Object.keys(obj).length</code> on any object to get its length. Object.keys returns an array containing all of the object <em>keys</em> (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 <em>function</em> for this. Let\'s get <em>creative</em> and write a <strong>method</strong> for it as well (along with a more convienient getter property):</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function objLength(obj)\r\n{\r\n  return Object.keys(obj).length;\r\n}\r\n\r\nconsole.log(objLength({a:1, b:"summit", c:"nonsense"}));\r\n\r\n// Works perfectly fine\r\nvar obj = new Object();\r\nobj[\'fish\'] = 30;\r\nobj[\'nullified content\'] = null;\r\nconsole.log(objLength(obj));\r\n\r\n// It also works your way, which is creating it using the Object constructor\r\nObject.prototype.getLength = function() {\r\n   return Object.keys(this).length;\r\n}\r\nconsole.log(obj.getLength());\r\n\r\n// You can also write it as a method, which is more efficient as done so above\r\n\r\nObject.defineProperty(Object.prototype, "length", {get:function(){\r\n    return Object.keys(this).length;\r\n}});\r\nconsole.log(obj.length);\r\n\r\n// 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()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 44114476, 'author': 'solanki...', 'author_id': 6390817, 'author_profile': 'https://Stackoverflow.com/users/6390817', 'pm_score': 5, 'selected': False, 'text': '<p>We can find the length of Object by using:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>const myObject = {};\nconsole.log(Object.values(myObject).length);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 44909574, 'author': 'MacroMan', 'author_id': 1171032, 'author_profile': 'https://Stackoverflow.com/users/1171032', 'pm_score': 2, 'selected': False, 'text': "<p>A nice way to achieve this (Internet\xa0Explorer\xa09+ only) is to define a magic getter on the length property:</p>\n<pre><code>Object.defineProperty(Object.prototype, &quot;length&quot;, {\n    get: function () {\n        return Object.keys(this).length;\n    }\n});\n</code></pre>\n<p>And you can just use it like so:</p>\n<pre><code>var myObj = { 'key': 'value' };\nmyObj.length;\n</code></pre>\n<p>It would give <code>1</code>.</p>\n"}, {'answer_id': 48319070, 'author': 'saurabhgoyal795', 'author_id': 7539786, 'author_profile': 'https://Stackoverflow.com/users/7539786', 'pm_score': 5, 'selected': False, 'text': '<p>Simply use this to get the <code>length</code>:</p>\n\n<pre><code>Object.keys(myObject).length\n</code></pre>\n'}, {'answer_id': 49683151, 'author': 'tdjprog', 'author_id': 4935426, 'author_profile': 'https://Stackoverflow.com/users/4935426', 'pm_score': 4, 'selected': False, 'text': '<pre><code>var myObject = new Object();\nmyObject["firstname"] = "Gareth";\nmyObject["lastname"] = "Simpson";\nmyObject["age"] = 21;\n</code></pre>\n\n<ol>\n<li>Object.values(myObject).length</li>\n<li>Object.entries(myObject).length</li>\n<li>Object.keys(myObject).length</li>\n</ol>\n'}, {'answer_id': 49730723, 'author': 'njmwas', 'author_id': 2529302, 'author_profile': 'https://Stackoverflow.com/users/2529302', 'pm_score': -1, 'selected': False, 'text': '<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = new Object();\r\nmyObject["firstname"] = "Gareth";\r\nmyObject["lastname"] = "Simpson";\r\nmyObject["age"] = 21;\r\n\r\nvar size = JSON.stringify(myObject).length;\r\n\r\ndocument.write(size);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>JSON.stringify(myObject)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 50608738, 'author': 'Mithu A Quayium', 'author_id': 2079914, 'author_profile': 'https://Stackoverflow.com/users/2079914', 'pm_score': 4, 'selected': False, 'text': '<p>The simplest way is like this:</p>\n<pre><code>Object.keys(myobject).length\n</code></pre>\n<p>Where myobject is the object of what you want the length of.</p>\n'}, {'answer_id': 50713932, 'author': 'PythonProgrammi', 'author_id': 6464947, 'author_profile': 'https://Stackoverflow.com/users/6464947', 'pm_score': 4, 'selected': False, 'text': '<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script&gt;\r\nmyObj = {"key1" : "Hello", "key2" : "Goodbye"};\r\nvar size = Object.keys(myObj).length;\r\nconsole.log(size);\r\n&lt;/script&gt;\r\n\r\n&lt;p id="myObj"&gt;The number of &lt;b&gt;keys&lt;/b&gt; in &lt;b&gt;myObj&lt;/b&gt; are: &lt;script&gt;document.write(size)&lt;/script&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This works for me:</p>\n\n<pre><code>var size = Object.keys(myObj).length;\n</code></pre>\n'}, {'answer_id': 54662407, 'author': 'Kamil Kiełczewski', 'author_id': 860099, 'author_profile': 'https://Stackoverflow.com/users/860099', 'pm_score': 0, 'selected': False, 'text': '<p><code>Object.keys</code> does <strong>not</strong> return the right result in case of object <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create" rel="nofollow noreferrer">inheritance</a>. To properly count object properties, including inherited ones, use <code>for-in</code>. For example, by the following function (related <a href="https://stackoverflow.com/a/54553880/860099">question</a>):</p>\n<pre><code>var objLength = (o,i=0) =&gt; { for(p in o) i++; return i }\n</code></pre>\n<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">\r\n<div class="snippet-code snippet-currently-hidden">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = new Object();\nmyObject["firstname"] = "Gareth";\nmyObject["lastname"] = "Simpson";\nmyObject["age"] = 21;\n\nvar child = Object.create(myObject);\nchild["sex"] = "male";\n\nvar objLength = (o,i=0) =&gt; { for(p in o) i++; return i }\n\nconsole.log("Object.keys(myObject):", Object.keys(myObject).length, "(OK)");\nconsole.log("Object.keys(child)   :", Object.keys(child).length, "(wrong)");\nconsole.log("objLength(child)     :", objLength(child), "(OK)");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 57525980, 'author': 'Paul', 'author_id': 5939653, 'author_profile': 'https://Stackoverflow.com/users/5939653', 'pm_score': -1, 'selected': False, 'text': "<p>I had a similar need to calculate the bandwidth used by objects received over a websocket. Simply finding the length of the Stringified object was enough for me.</p>\n\n<pre><code>websocket.on('message', data =&gt; {\n    dataPerSecond += JSON.stringify(data).length;\n}\n</code></pre>\n"}, {'answer_id': 57839252, 'author': 'shaheb', 'author_id': 2786194, 'author_profile': 'https://Stackoverflow.com/users/2786194', 'pm_score': 4, 'selected': False, 'text': '<p>Use <code>Object.keys(myObject).length</code> to get the length of object/array</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = new Object();\nmyObject["firstname"] = "Gareth";\nmyObject["lastname"] = "Simpson";\nmyObject["age"] = 21;\n\nconsole.log(Object.keys(myObject).length); //3</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 59694573, 'author': 'Soura Ghosh', 'author_id': 9229338, 'author_profile': 'https://Stackoverflow.com/users/9229338', 'pm_score': 3, 'selected': False, 'text': '<pre><code>const myObject = new Object();\nmyObject["firstname"] = "Gareth";\nmyObject["lastname"] = "Simpson";\nmyObject["age"] = 21;\n\nconsole.log(Object.keys(myObject).length)\n\n// o/p 3\n</code></pre>\n'}, {'answer_id': 60540719, 'author': 'Sheelpriy', 'author_id': 2542562, 'author_profile': 'https://Stackoverflow.com/users/2542562', 'pm_score': 2, 'selected': False, 'text': '<p>With the ECMAScript\xa06 in-built Reflect object, you can easily count the properties of an object:</p>\n<pre><code>Reflect.ownKeys(targetObject).length\n</code></pre>\n<p>It will give you the length of the target object\'s own properties (<em>important</em>).</p>\n<pre><code>Reflect.ownKeys(target)\n</code></pre>\n<blockquote>\n<p>Returns an array of the target object\'s own (not inherited) property\nkeys.</p>\n</blockquote>\n<p>Now, what does that mean? To explain this, let\'s see this example.</p>\n<pre><code>function Person(name, age){\n  this.name = name;\n  this.age = age;\n}\n\nPerson.prototype.getIntro= function() {\n  return `${this.name} is ${this.age} years old!!`\n}\n\nlet student = new Person(\'Anuj\', 11);\n\nconsole.log(Reflect.ownKeys(student).length) // 2\nconsole.log(student.getIntro()) // Anuj is 11 years old!!\n</code></pre>\n<p>You can see here, it returned only its own properties while the object is still inheriting the property from its parent.</p>\n<p>For more information, refer this: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect" rel="nofollow noreferrer">Reflect API</a></p>\n'}, {'answer_id': 64231717, 'author': 'Shashwat Gupta', 'author_id': 7765900, 'author_profile': 'https://Stackoverflow.com/users/7765900', 'pm_score': 2, 'selected': False, 'text': '<p>Simple one liner:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(Object.values({id:"1",age:23,role_number:90}).length);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 67136236, 'author': 'Rashed Rahat', 'author_id': 10427807, 'author_profile': 'https://Stackoverflow.com/users/10427807', 'pm_score': 2, 'selected': False, 'text': '<p>Try: <code>Object.values(theObject).length</code></p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>const myObject = new Object();\nmyObject["firstname"] = "Gareth";\nmyObject["lastname"] = "Simpson";\nmyObject["age"] = 21;\nconsole.log(Object.values(myObject).length);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 69669301, 'author': 'Coni', 'author_id': 16932102, 'author_profile': 'https://Stackoverflow.com/users/16932102', 'pm_score': -1, 'selected': False, 'text': '<pre><code> vendor = {1: &quot;&quot;, 2: &quot;&quot;}\n const keysArray = Object.keys(vendor)\n const objectLength = keysArray.length\n console.log(objectLength)\n Result 2\n</code></pre>\n'}, {'answer_id': 70413307, 'author': 'dazzafact', 'author_id': 1163485, 'author_profile': 'https://Stackoverflow.com/users/1163485', 'pm_score': 1, 'selected': False, 'text': "<p>Here you can give any kind of varible array,object,string</p>\n<pre><code>function length2(obj){\n    if (typeof obj==='object' &amp;&amp; obj!== null){return Object.keys(obj).length;}\n   //if (Array.isArray){return obj.length;}\n    return obj.length;\n\n}\n</code></pre>\n"}, {'answer_id': 71957503, 'author': 'Ran Turner', 'author_id': 7494218, 'author_profile': 'https://Stackoverflow.com/users/7494218', 'pm_score': 3, 'selected': False, 'text': '<p>Using the <code>Object.entries</code> method to get length is one way of achieving it</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>const objectLength = obj =&gt; Object.entries(obj).length;\n\nconst person = {\n    id: 1,\n    name: \'John\',\n    age: 30\n}\n  \nconst car = {\n    type: 2,\n    color: \'red\',\n}\n\nconsole.log(objectLength(person)); // 3\nconsole.log(objectLength(car)); // 2</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}]
['https://Stackoverflow.com/questions/5223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147/']