Categories
javascript javascript-objects

Length of a JavaScript object

2841

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;

3

  • 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, 2013 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

    May 10, 2019 at 19:31


  • 1

    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.

    Mar 15, 2021 at 10:28

3130

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.


16

  • 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, 2011 at 11:30


  • 19

    @vsync You are very correct. One should always implement necessary sanity checks 🙂

    – Tres

    Jun 24, 2011 at 2:03


  • 159

    Why is everyone ignoring this: Object.keys(obj).length

    Feb 25, 2015 at 0:14

  • 36

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

    May 9, 2015 at 1:53

  • 23

    @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/3123303

    Jan 19, 2016 at 9:08

1998

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

18

  • 25

    why not? from what I know, it is a standard: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…

    – vsync

    Jun 6, 2011 at 11:51

  • 109

    It’s not a universally implemented method, but you can check which browser supports it with this table.

    – aeosynth

    Jun 6, 2011 at 19:08

  • 26

    time to switch to firefox = unfortunately, you switching doesn’t mean your website’s users will…

    – mdup

    Aug 13, 2012 at 11:25

  • 87

    @ripper234 no IE support = time to polyfill

    Dec 13, 2012 at 6:27

  • 22

    @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, 2014 at 15:17

307

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;
};

6

  • 8

    _.size() was the perfect solution for my Meteor project, which has underscore.js support.

    Aug 1, 2013 at 17:05

  • 4

    I 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

    Nov 20, 2013 at 20:51

  • 3

    Underscore > (all -[‘lo-dash’])

    – Rayjax

    Apr 11, 2014 at 8:13

  • underscorejs, things that should be under js 🙂

    – Minhaj

    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

    Feb 12, 2017 at 19:56