Sometimes, we want to get the length of a JavaScript associative array.
In this article, we’ll look at how to get the length of a JavaScript associative array.
How to get the length of a JavaScript associative array?
To get the length of a JavaScript associative array, we use the Object.keys
method.
For instance, we write
const myObject = {};
myObject["q101"] = "Your name?";
myObject["q102"] = "Your age?";
myObject["q103"] = "Your school?";
console.log(Object.keys(myObject).length);
to define the myObject
object.
Then we call Object.keys
with myObject
to return an array of non-inherited property key strings.
And then we get the length
property of that to get the number of non-inherited properties in the object.
Conclusion
To get the length of a JavaScript associative array, we use the Object.keys
method.