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];
}
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.
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.
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.
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.
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.
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With