2995

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;
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
Gareth Simpson
  • 36,943
  • 12
  • 47
  • 50
  • 1
    @neitony - that's kinda true, but so many people are used to PHP's "associative array" that they might assume it means "*ordered* associative map", when JS objects are in fact unordered. – cloudfeet Jul 23 '13 at 16:53
  • 4
    In the above example, myObject.length is undefined, at least in a browser environment. That's why it isn't valid, @AdrianM – Andrew Koster May 10 '19 at 19:31
  • 3
    Variants of `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. – Sebastian Simon Mar 15 '21 at 10:28

44 Answers44

3343

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.


mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • 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 defined – vsync Jun 14 '11 at 11:30
  • 19
    @vsync You are very correct. One should always implement necessary sanity checks :) – Tres Jun 24 '11 at 02:03
  • 1
    I wrapped this answer as a jQuery plugin, for those that don't like messing around with `Object`: http://stackoverflow.com/a/11346637/11236 – ripper234 Jul 05 '12 at 14:39
  • 3
    @James Coglan why are you declaring the function within Object class and not just as a regular function ? i.e. function getSize(obj) {...} ? – alexserver Mar 14 '13 at 18:07
  • 3
    @alexserver I guess he's just maintaining proper structure. This function returns size of an object so it makes sense to make it an extension of Object. Keep your code clean and maintainable. – Pijusn May 31 '13 at 15:55
  • This method is however more buggy, especially when hasownprop seldom clears out when deleting object keys with delete keyword. – Clain Dsilva Jan 28 '14 at 14:13
  • 159
    Why is everyone ignoring this: `Object.keys(obj).length` – Muhammad Umer Feb 25 '15 at 00: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 May 09 '15 at 01:53
  • 1
    Re Object.keys(obj).length: That's because IE8 don't support this method. – stonyau Jan 09 '16 at 06:06
  • 25
    @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. https://support.microsoft.com/en-us/kb/3123303 – Lukas Liesis Jan 19 '16 at 09:08
  • Yeah, it's 2017. Nobody should be using anything other than `Object.keys(myObj).length`. This answer was correct in 2008 but not any more. – Ryan Shillington Jul 26 '17 at 14:46
  • 1
    Not sure if it has been mentioned already because TL;DR but extending JavaScript's built in objects is frowned upon. – Matthew Layton Apr 04 '18 at 08:52
  • Nor `Object.keys()` nor `getOwnProperty*()` functions will give you the correct answer if their parameter will be `new Date()`, which of course IS an object (`typeof new Date() === 'object'`). Freaky… – Przemek May 20 '18 at 20:27
  • 2
    @Przemek I don't understand what you mean. `Object.keys(new Date()).length` gives `0`, `x = new Date(); Object.keys(x).length` also gives `0`. – Phlarx May 23 '18 at 18:48
2026

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
Jeromy French
  • 11,812
  • 19
  • 76
  • 129
aeosynth
  • 20,750
  • 2
  • 21
  • 18
  • 25
    why not? from what I know, it is a standard: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys – vsync Jun 06 '11 at 11:51
  • 109
    It's not a universally *implemented* method, but you can check which browser supports it with [this table](http://kangax.github.com/es5-compat-table/). – aeosynth Jun 06 '11 at 19:08
  • 11
    @ripper234 That depends on your requirements. – KOVIKO Feb 01 '12 at 21:12
  • 8
    According to that table, IE8 supports 4 / 34 of the "standards". Wow. – Ben Jul 13 '12 at 02:26
  • 27
    time to switch to firefox = unfortunately, you switching doesn't mean your website's users will... – mdup Aug 13 '12 at 11:25
  • 87
    @ripper234 no IE support = time to polyfill – John Dvorak Dec 13 '12 at 06:27
  • 7
    `if (typeof Object.keys != 'function') { Object.keys = function(obj) { var ret = []; for (var x in obj) { if (obj.hasOwnProperty(x)) { ret[ret.length] = x; } } return ret; } }` – EpicVoyage May 08 '13 at 14:03
  • 1
    @ripper234: No IE8, `Object.keys or= (obj) -> key for own key of obj` ([CoffeeScript](http://coffeescript.org/), you can easily copy generated output). – Konrad Borowski Sep 01 '13 at 10:51
  • 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 Mar 21 '14 at 15:17
  • 1
    creating a new array just to count the length of it? It's an overkill of resources – Steel Brain Jan 19 '15 at 05:50
  • 5
    The specification says that the keys() method returns only the names of the the object's own properties, so using this method would avoid the hasOwnProperty check. – John Apr 02 '15 at 21:06
  • @SteelBrain - Don't optimize prematurely. If you need to conserve resources then I'd recommend maintaining a separate length variable (or use a for loop) but that's probably only necessary when dealing with huge hashes. – PhilT Apr 14 '15 at 08:32
  • 9
    @albanx That attitude won't get you far in web development. Websites are made for the visitors, not for the developers. – hodgef May 20 '15 at 18:32
  • 2
    Great polyfill for legacy IE at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object – Chaoix Aug 06 '15 at 14:52
  • 1
    `map` creates an array with the same length. Did you mean `filter`? – Oriol Nov 28 '16 at 23:03
  • Even if you worried about `.hasOwnProperty*()` functions, you wouldn't get the right answer if the object you wanted to check against, was `new Date()`. – Przemek May 20 '18 at 20:26
  • In case speed is a concern for you it turns out `Object.values(myObject).length` is faster. At least in Chrome `v67`. https://gist.github.com/flekschas/5aad97d1c2520db7af0a9623deec005f – F Lekschas Jul 31 '18 at 15:01
313

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;
};
ripper234
  • 222,824
  • 274
  • 634
  • 905
70

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;
Joon
  • 9,346
  • 8
  • 48
  • 75
  • 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 use `Object.getOwnPropertyNames()` instead. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys – John Slegers Mar 07 '16 at 12:40
48

Simply use this to get the length:

Object.keys(myObject).length
Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
saurabhgoyal795
  • 1,287
  • 12
  • 12
44

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".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jj33
  • 7,543
  • 2
  • 38
  • 42
38

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
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
venkat7668
  • 2,657
  • 1
  • 22
  • 26
  • 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 Feb 26 '15 at 16:07
31

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. ;)

Pang
  • 9,564
  • 146
  • 81
  • 122
DanMan
  • 11,323
  • 4
  • 40
  • 61
  • I think this is the best solution as it doesn't require looping with 'for' which could be costly if the array is big – Emeka Mbah Jun 01 '16 at 19:53
29

We can find the length of Object by using:

const myObject = {};
console.log(Object.values(myObject).length);
costaparas
  • 5,047
  • 11
  • 16
  • 26
solanki...
  • 4,982
  • 2
  • 27
  • 29
  • 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 Jun 06 '21 at 21:55
25

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++;
Kev
  • 118,037
  • 53
  • 300
  • 385
doekman
  • 18,750
  • 20
  • 65
  • 86
24

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ally
  • 4,894
  • 8
  • 37
  • 45
  • 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 function – Panos Theof Oct 26 '14 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 against `length`, but I guess that would be the same if it was a standard array too. Overriding `hasOwnProperty` on any object would most likely produce an undesired result. – Ally Oct 27 '14 at 00:03
20

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
kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59
Oriol
  • 274,082
  • 63
  • 437
  • 513
20

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
double-beep
  • 5,031
  • 17
  • 33
  • 41
shaheb
  • 557
  • 5
  • 12
19

Use:

var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
obj = Object.keys(myArray).length;
console.log(obj)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mahendra Kulkarni
  • 1,437
  • 2
  • 26
  • 35
19

<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;
RAGINROSE
  • 694
  • 8
  • 13
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34
18

The simplest way is like this:

Object.keys(myobject).length

Where myobject is the object of what you want the length of.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mithu A Quayium
  • 729
  • 5
  • 14
18

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.

Jānis Elmeris
  • 1,975
  • 1
  • 25
  • 43
17

@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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Polsonby
  • 22,825
  • 19
  • 59
  • 74
17

Using the Object.entries method to get 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
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
15

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
abo-elleef
  • 2,100
  • 1
  • 14
  • 16
  • 2
    This 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 Sep 03 '15 at 09:54
  • 2
    Unfortunately, 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 defined – chim Sep 03 '15 at 10:14
  • http://stackoverflow.com/questions/32372685/javascript-keys-function-documentation – chim Sep 03 '15 at 10:17
  • 1
    How is this different from [aeosynth's answer](http://stackoverflow.com/questions/5223/length-of-a-javascript-object-or-associative-array/5527037#5527037)? – Peter Mortensen Sep 17 '16 at 18:32
14
var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
  1. Object.values(myObject).length
  2. Object.entries(myObject).length
  3. Object.keys(myObject).length
tdjprog
  • 706
  • 6
  • 11
13

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--; }}
}
Jerry
  • 131
  • 1
  • 2
12

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pcnate
  • 1,694
  • 1
  • 18
  • 34
  • 4
    The OP has not asked for a AngularJS version. This is not a valid answer to the question. – hodgef Dec 04 '15 at 21:07
11
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

console.log(Object.keys(myObject).length)

// o/p 3
Soura Ghosh
  • 879
  • 1
  • 9
  • 16
10

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:

  1. Run either Object.keys() to get an array that contains the names of only those properties that are enumerable or Object.getOwnPropertyNames() if you want to also include the names of properties that are not enumerable.
  2. 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.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
10

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
wade harrell
  • 101
  • 1
  • 3
7

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/

Sherzod
  • 5,041
  • 10
  • 47
  • 66
  • 6
    `Object.prototype` - bad idea. – Dziad Borowy Oct 14 '13 at 10:50
  • @tborychowski can you please explain why? – Mohamad Mar 05 '14 at 13:09
  • here's one article: http://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 Mar 05 '14 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions). My recommendation: follow [these examples](https://stackoverflow.com/a/46491279/4642212) which demonstrate how to add a method that behaves as closely as possible like built-in methods. – Sebastian Simon May 09 '20 at 09:43
6

You can always do Object.getOwnPropertyNames(myObject).length to get the same result as [].length would give for normal array.

Pian0_M4n
  • 2,505
  • 31
  • 35
  • 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 use `Object.getOwnPropertyNames()` instead. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys – John Slegers Mar 07 '16 at 12:39
  • 3
    How is this different from [aeosynth's answer](http://stackoverflow.com/questions/5223/length-of-a-javascript-object-or-associative-array/5527037#5527037)? – Peter Mortensen Sep 17 '16 at 18:35
5

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()
Mystical
  • 2,505
  • 2
  • 24
  • 43
  • 4
    How is this different from [aeosynth's answer](http://stackoverflow.com/questions/5223/length-of-a-javascript-object-or-associative-array/5527037#5527037)? – Peter Mortensen Sep 17 '16 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](http://stackoverflow.com/questions/5223/length-of-a-javascript-object-or-associative-array/5527037#5527037) doesn't. – Mystical Sep 18 '16 at 01: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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions). My recommendation: follow [these examples](https://stackoverflow.com/a/46491279/4642212) which demonstrate how to add a method that behaves as closely as possible like built-in methods. – Sebastian Simon May 09 '20 at 09:45
  • Also, how is writing a method “more efficient”? – Sebastian Simon May 09 '20 at 09:46
4

A nice way to achieve this (Internet Explorer 9+ only) is to define a magic getter on the length property:

Object.defineProperty(Object.prototype, "length", {
    get: function () {
        return Object.keys(this).length;
    }
});

And you can just use it like so:

var myObj = { 'key': 'value' };
myObj.length;

It would give 1.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MacroMan
  • 2,335
  • 1
  • 27
  • 36
  • 2
    Arguments against prototype modification aside, I personally have NEVER had a bug caused by it and for me is one of the strong points of JavaScript. – MacroMan Aug 13 '19 at 09:31
3

Below is a version of James Coglan's answer in CoffeeScript for those who have abandoned straight JavaScript :)

Object.size = (obj) ->
  size = 0
  size++ for own key of obj
  size
Eric Anderson
  • 3,692
  • 4
  • 31
  • 34
  • 2
    You probably wanted to say `size++ for own key of obj` (`own key` being syntax sugar in CoffeeScript). Using `hasOwnProperty` directly from the object is dangerous, as it breaks when object actually has such property. – Konrad Borowski Sep 01 '13 at 10:47
  • 2
    The OP didn't ask for a CoffeeScript version, nor it is tagged as such. This is not a valid answer to the question. – hodgef Dec 04 '15 at 21:01
3

Property

Object.defineProperty(Object.prototype, 'length', {
    get: function () {
        var size = 0, key;
        for (key in this)
            if (this.hasOwnProperty(key))
                size++;
        return size;
    }
});

Use

var o = {a: 1, b: 2, c: 3};
alert(o.length); // <-- 3
o['foo'] = 123;
alert(o.length); // <-- 4
Community
  • 1
  • 1
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
  • 1
    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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions). My recommendation: follow [these examples](https://stackoverflow.com/a/46491279/4642212) which demonstrate how to add a method that behaves as closely as possible like built-in methods. – Sebastian Simon May 09 '20 at 09:34
3

With the ECMAScript 6 in-built Reflect object, you can easily count the properties of an object:

Reflect.ownKeys(targetObject).length

It will give you the length of the target object's own properties (important).

Reflect.ownKeys(target)

Returns an array of the target object's own (not inherited) property keys.

Now, what does that mean? To explain this, let's see this example.

function Person(name, age){
  this.name = name;
  this.age = age;
}

Person.prototype.getIntro= function() {
  return `${this.name} is ${this.age} years old!!`
}

let student = new Person('Anuj', 11);

console.log(Reflect.ownKeys(student).length) // 2
console.log(student.getIntro()) // Anuj is 11 years old!!

You can see here, it returned only its own properties while the object is still inheriting the property from its parent.

For more information, refer this: Reflect API

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sheelpriy
  • 1,675
  • 17
  • 28
3

Try: Object.values(theObject).length

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
console.log(Object.values(myObject).length);
Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
2

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.

function uberject(obj){
    this._count = 0;
    for(var param in obj){
        this[param] = obj[param];
        this._count++;
    }
}

uberject.prototype.getLength = function(){
    return this._count;
};

var foo = new uberject({bar:123,baz:456});
alert(foo.getLength());
Pang
  • 9,564
  • 146
  • 81
  • 122
Ron Sims II
  • 566
  • 5
  • 10
2

Simple one liner:

console.log(Object.values({id:"1",age:23,role_number:90}).length);
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
Shashwat Gupta
  • 5,071
  • 41
  • 33
1

Simple solution:

  var myObject = {};      // ... your object goes here.

  var length = 0;

  for (var property in myObject) {
    if (myObject.hasOwnProperty(property)){
      length += 1;
    }
  };

  console.log(length);    // logs 0 in my example.
stylesenberg
  • 519
  • 3
  • 16
1

Here you can give any kind of varible array,object,string

function length2(obj){
    if (typeof obj==='object' && obj!== null){return Object.keys(obj).length;}
   //if (Array.isArray){return obj.length;}
    return obj.length;

}
dazzafact
  • 2,570
  • 3
  • 30
  • 49
0

The solution work for many cases and cross browser:

Code

var getTotal = function(collection) {

    var length = collection['length'];
    var isArrayObject =  typeof length == 'number' && length >= 0 && length <= Math.pow(2,53) - 1; // Number.MAX_SAFE_INTEGER

    if(isArrayObject) {
        return collection['length'];
    }

    i= 0;
    for(var key in collection) {
        if (collection.hasOwnProperty(key)) {
            i++;
        }
    }

    return i;
};

Data Examples:

// case 1
var a = new Object();
a["firstname"] = "Gareth";
a["lastname"] = "Simpson";
a["age"] = 21;

//case 2
var b = [1,2,3];

// case 3
var c = {};
c[0] = 1;
c.two = 2;

Usage

getLength(a); // 3
getLength(b); // 3
getLength(c); // 2
christian Nguyen
  • 1,530
  • 13
  • 11
0

Object.keys does not return the right result in case of object inheritance. To properly count object properties, including inherited ones, use for-in. For example, by the following function (related question):

var objLength = (o,i=0) => { for(p in o) i++; return i }

var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

var child = Object.create(myObject);
child["sex"] = "male";

var objLength = (o,i=0) => { for(p in o) i++; return i }

console.log("Object.keys(myObject):", Object.keys(myObject).length, "(OK)");
console.log("Object.keys(child)   :", Object.keys(child).length, "(wrong)");
console.log("objLength(child)     :", objLength(child), "(OK)");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

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
Jerry
  • 1,005
  • 2
  • 13
-1
 vendor = {1: "", 2: ""}
 const keysArray = Object.keys(vendor)
 const objectLength = keysArray.length
 console.log(objectLength)
 Result 2
Coni
  • 45
  • 2
  • 1
    [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Stephen Ostermiller Oct 22 '21 at 00:16
-2

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.

websocket.on('message', data => {
    dataPerSecond += JSON.stringify(data).length;
}
Paul
  • 83
  • 10
-4

var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

var size = JSON.stringify(myObject).length;

document.write(size);

JSON.stringify(myObject)
njmwas
  • 1,111
  • 14
  • 15
  • 2
    the question resolved around the number of properties. your answer just shows what the length of one (out of many!) serialized forms is. – oligofren Sep 21 '18 at 08:50
  • On explanation would be in order. You can [edit your answer](https://stackoverflow.com/posts/49730723/edit). – Peter Mortensen Jul 10 '20 at 18:51