gopi1410 gopi1410 - 1 year ago 97
Javascript Question

Length of a javascript associative array

I have a js associative array (or some may prefer to call it as an object) like, say

var quesArr=new Array();
quesArr["q101"]="Your name?";
quesArr["q102"]="Your age?";
quesArr["q103"]="Your school?";

Is there any built in function that could get the length of this array, or any solution in jQuery or other library? Currently quesArr.length would give 0, as most of you must be knowing.

Please dont suggest iterating over the entire array/object as mentioned in this question, because the array/object which I have is very large.

Is there any way I could proceed with this?

Answer Source

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 is an ES5 and higher feature, Object.keys, which you could use like this:

console.log(Object.keys(quesArr).length); // "3"

Object.keys returns an array of the names of an object's own enumerable properties. But internally of course it's that loop you didn't want to use (and the polyfill for it for pre-ES5 environments uses a loop, of course).

There's also another ES5+ feature, Object.getOwnPropertyNames, which returns an array of the object's "own" property names regardless of whether they're enumerable.

FWIW, unless you're going to use the Array features of the object, don't make it an array. Instead:

var quesArr={};
quesArr["q101"]="Your name?";
quesArr["q102"]="Your age?";
quesArr["q103"]="Your school?";

Those keys don't have to be given as string literals in square brackets, either, if you don't want them to be (whether use use an array or a plain object):

var quesArr={};
quesArr.q101="Your name?";
quesArr.q102="Your age?";
quesArr.q103="Your school?";

But you can use the other notation if you prefer; they're exactly equivalent except that with dotted notation the keys must be valid identifiers (in bracketed notation they can be anything).

You can even do this:

var quesArr={
    q101: "Your name?",
    q102: "Your age?",
    q103: "Your school?"

or (if the keys won't be valid identifiers):

var quesArr={
    "q101": "Your name?",
    "q102": "Your age?",
    "q103": "Your school?"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download