I am looking to create a JavaScript object (associative array) with alphabets as keys. What is the best way to accomplish this?
Example -
obj[a] = 'somevalue'
obj[b] = 'somevalue'
...
obj[z]= 'some value'
Assigning alphabets as keys dynamically.
An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var 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.
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.
While it is clear that arrays are JavaScript objects, JavaScript also allows objects and their properties to be accessed as if they were arrays. Normal JavaScript arrays index their values in order using integer indices.
Here's a quick and lazy way to create the object:
var a = 97;
var charArray = {};
for (var i = 0; i<26; i++)
charArray[String.fromCharCode(a + i)] = String.fromCharCode(a + i);
console.log(charArray);
http://jsfiddle.net/V2B7S/
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