William Sham
William Sham

Reputation: 13239

javascript using numeric array as associate array

In Javascript, I have an array of objects, users, such that users[1].name would give me the name of that user.

I want to use the ID of that user as the index instead of the ever increasing counter. For example, I can initiate the first user as users[45].

However, I found that once I do users[45], javascript would turn it into a numeric array, such that when I do users.length, I get 46.

Is there anyway to force it to treat the number as string in this case. (" " doesn't work)?

Upvotes: 3

Views: 5466

Answers (2)

Jon Gauthier
Jon Gauthier

Reputation: 25572

You cannot use arrays for this sort of function in JavaScript — for more information, see "Javascript Does Not Support Associative Arrays."

Make sure you initialize the users variable as an Object instead. In this object you can store the arbitrary, non-sequential keys.

var users = new Object();

// or, more conveniently:
var users = {};

users[45] = { name: 'John Doe' };

To get the number of users in the object, here's a function stolen from this SO answer:

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

var users = {};
// add users..

alert(Object.size(users));

Upvotes: 11

jfriend00
jfriend00

Reputation: 707308

Hans has the right answer here. Use keys on an object, not an array. I'd suggest you read these two references:

http://www.quirksmode.org/js/associative.html and http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/

Trying to make an associative array out of an array object is non-standard and can cause problems (for example .length will be zero). Use keys on an object instead.

Upvotes: 2

Related Questions