Jimbo
Jimbo

Reputation: 22984

Efficient syntax for populating a javascript associative array

I have an autocomplete text box that users can type an item code into and need to find out what the id number of that item code is in javascript.

An associative array is the way I would imagine it should be done, but the following seems a little long winded and I'm hoping someone has a better way to do it or shorthand of what I have below:

var itemIds = new Array();
itemIds["item1"] = 15;
itemIds["item2"] = 40;
itemIds["item3"] = 72;
...

function getItemId(code){
    return itemIds[code];
}

Upvotes: 19

Views: 10310

Answers (2)

Simon Steele
Simon Steele

Reputation: 11608

Try using Object Literal notation to specify your lookup like this:

var itemIds = {
    "item1" : 15,
    "item2" : 40
    ...
};

Access should still work like this:

var item1Value = itemIds["item1"];

Upvotes: 2

Skilldrick
Skilldrick

Reputation: 70869

What you're doing isn't an array - it's an object (objects in JavaScript are the equivalent-ish of associative arrays in PHP).

You can use JavaScript object literal syntax:

var itemIds = {
    item1: 15,
    item2: 40,
    item3: 72
};

JavaScript object members can be accessed via dot notation or array subscript, like so:

itemIds.item1;
itemIds['item1'];

You'll need to use the second option if you've got the member name as a string.

Upvotes: 23

Related Questions