Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
}
like image 324
Jimbo Avatar asked Sep 30 '10 13:09

Jimbo


People also ask

What syntax is used to create an associative array in JavaScript?

An associative array is declared or dynamically createdvar arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.

What is an associative array include syntax?

An associative array is an array with string keys rather than numeric keys. Associative arrays are dynamic objects that the user redefines as needed. When you assign values ​​to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array.

What is are the ways for declaring associative array?

The associative array is declared using an array keyword. The key value in the array is declared using the '=>' arrow. There are two ways to create an associative array.

Are there associative arrays in JavaScript?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.


2 Answers

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.

like image 184
Skilldrick Avatar answered Sep 29 '22 07:09

Skilldrick


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"];
like image 26
Simon Steele Avatar answered Sep 29 '22 05:09

Simon Steele