Friday 28 October 2016

Length of a JavaScript object



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;


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







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 which 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. Main benefit of Symbol type is 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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...