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["
You can always do Object.getOwnPropertyNames(myObject).length
to get the same result as [].length
would give for normal array.
The simplest way is like this:
Object.keys(myobject).length
Where myobject is the object of what you want the length of.
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
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
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
.
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