views:

33

answers:

2

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 Im 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];
}
+1  A: 

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"];
Simon Steele
Arg... I wasn't fast enough.
some
Technically, JSON is the use of JavaScript object and array literals for data exchange - what you're showing is an object literal.
Skilldrick
Oh, I assumed from the "Notation" bit in the name that it defined the syntax. Object Literal it is!
Simon Steele
@Simon JSON is the name that Douglas Crockford gave to the data format, taking the syntax from JavaScript object literals. I can understand the confusion though!
Skilldrick
+2  A: 

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.

Skilldrick