Length of JavaScript object

I have a JavaScript object. Is there a built-in or recognized best practice to get the length of this object? const myObject = new Object(); myObject...

I have a JavaScript object. Is there a built-in or recognized best practice to get the length of this object?

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

#1 building

Update: if you are using Underscore.js (recommended, it's lightweight!) , then you can

_.size(); => 3

If not, and you don't want to mess up the Object properties for any reason, and you are already using jQuery, you can also access a plug-in:

$.assocArraySize = function(obj) { // http://stackoverflow.com/a/6700/11236 var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; };

#2 building

Here's James Coglan's answer in CoffeeScript for those who give up direct JavaScript:)

Object.size = (obj) -> size = 0 size++ for own key of obj size

#3 building

This is a different version of James Cogan's answer. There is no need to pass parameters, just prototype the Object class and make the code more concise.

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/

#4 building

This is a completely different solution for more modern browsers only (IE9 +, Chrome, Firefox 4 +, Opera 11.60 +, Safari 5.1 +)

see jsFiddle

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

#5 building

This is the most cross browser solution.

This is better than the accepted answer because it uses native Object.keys, if any. So it's the fastest of 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;

3 December 2019, 11:54 | Views: 6171

Add new comment

For adding a comment, please log in
or create account

0 comments