I have a JavaScript associative array (or some may prefer to call it an object) like, say
var quesArr = new Array();
quesArr["q101"] = "Your name?";
quesArr["q102"] = "Your age?";
quesArr["q103"] = "Your school?";
Is there a built-in function that could get the length of this array, or a solution in jQuery or another library? Currently quesArr.length would give 0, as most of you must be knowing.
Please don’t suggest iterating over the entire array/object as mentioned in this question, because the array/object which I have is very large.
Is there a way I could proceed with this?
No, there is no built-in property that tells you how many properties the object has (which is what you’re looking for). The closest I can think of for plain objects (keep reading for an alternative) are things that return arrays of property keys (which you can then get
lengthfrom):Object.keys– Returns an array of the object’s own, enumerable, string-keyed properties.Object.getOwnPropertyNames– LikeObject.keys, but includes non-enumerable properties as well.Object.getOwnPropertySymbols– LikeObject.getOwnPropertyNames, but for Symbol-keyed properties instead of string-keyed properties.Reflect.ownKeys– Returns an array of an object’s own properties (whether or not they’re enumerable, and whether they’re keyed by strings or Symbols).For instance, you could use
Reflect.ownKeyslike this:Notice that showed 4, not 3, because of the built-in
lengthproperty of arrays. Since you don’t seem to be using theArrayfeatures of the object, don’t make it an array. You could make it a plain object:But since you want to know how many things are in it, you might consider using a
Map, because unlike objects,Mapinstances do have a property telling you how many entries they have in them:size.