19

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];
}
blahdiblah
  • 33,069
  • 21
  • 98
  • 152
Jimbo
  • 22,379
  • 42
  • 117
  • 159
  • 1
    It's not necessary to declare `itemIds` as `Array` object. After all you are just adding properties to an object. Since JavaScript object can be seen as a `container for key-value pairs`, any JavaScript object will do. – smwikipedia Dec 04 '15 at 03:59

2 Answers2

23

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
  • 69,215
  • 34
  • 177
  • 229
2

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
  • 11,558
  • 4
  • 45
  • 67
  • 1
    Technically, JSON is the use of JavaScript object and array literals for data exchange - what you're showing is an object literal. – Skilldrick Sep 30 '10 at 13:57
  • Oh, I assumed from the "Notation" bit in the name that it defined the syntax. Object Literal it is! – Simon Steele Sep 30 '10 at 14:01
  • 3
    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 Sep 30 '10 at 14:03