5

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
thinking_hydrogen
  • 189
  • 1
  • 5
  • 15

6 Answers6

12

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/

Thach Mai
  • 915
  • 1
  • 6
  • 16
  • I needed that one as PHP so I converted it. But I stumbled upon the `fromCharCode` which does not exist on PHP. So you can use the custom function answered at http://stackoverflow.com/a/9878531/684932 to do so and works like a charm. – RaphaelDDL Nov 06 '12 at 20:43
  • This is awesome – rpivovar Jun 22 '20 at 21:43
4
var obj = { };
obj['A'] = 'letter A';
obj['B'] = 'letter B';
obj['C'] = 'letter C';

or:

var obj = [ ];
obj['A'] = 'letter A';
obj['B'] = 'letter B';
obj['C'] = 'letter C';

and then:

alert(obj.B);

or the equivalent:

alert(obj['B']);

I would use the { } syntax for non-integer based indexes though. Why? Because there are some real gotchas when you use [ ] with non-integer indexes, like this one:

var obj = [ ];
obj['A'] = 'letter A';
obj['B'] = 'letter B';
obj['C'] = 'letter C';
alert(obj.length);

Guess what will be printed? Yes, you guessed it: 0.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for the very quick response Darin. I'm aware of doing it this way but was wondering if there is a better way of achieving this. In PHP, this can be done easily by using range function as in range('a','z'). – thinking_hydrogen May 16 '12 at 11:05
  • 1
    In javascript you could either use an Array (`[]`) or an Object (`{}`) knowing that an Array is actually an Object with some gotchas. So be careful. Use arrays for integer based indexes and objects for non-integer base indexes. – Darin Dimitrov May 16 '12 at 11:07
  • The preferred style is to use `[]` for arrays and `{}` for objects, not to call `new Object()` and `new Array()`. The constructors behave in... unexpected ways with certain combinations of parameters. (Documented and reliable unexpected ways, but every time you see that construct, you have to ask "what are they trying to do?") – Sean McMillan May 16 '12 at 11:12
  • Agreed. I have updated my answer to use the preferred syntax. – Darin Dimitrov May 16 '12 at 11:19
  • Thanks for your inputs. I am looking for something similar to Thack_Mai and Jake's solution. – thinking_hydrogen May 16 '12 at 11:23
4
var hash = {};
hash["abcdefghijklmnopqrstuvwxyz"] = "something";
hash["בגדהוזחטיךכלםמןנסעףפץצקרשת"] = "something else";
hash["АБВГДЕЖЅZЗИІКЛМНОПРСТȢѸФХѾЦЧШЩЪꙐЬѢꙖѤЮѦѪѨѬѠѺѮѰѲѴ"] = "something else";
Andrew Bullock
  • 36,616
  • 34
  • 155
  • 231
2

First create an array of letters using the trick Thack Mai used:

var associateArray = []  
for (i = 65; i <= 90; i++) {
    associateArray[i-65] = String.fromCharCode(i).toLowerCase()
}

Then map values to any of the letters you want to map values to

associateArray['a'] = 1
associateArray['b'] = 2

This creates the type of object used in browsers for CSSStyleDeclaration. It can be iterated over like so

for (var i = 0; i < associateArray.length; i++) {
    console.log(associateArray[associateArray[i]])
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jake
  • 558
  • 4
  • 12
2

You can use reduce to create an associative array:

const dict = Array.from(new Array(26))
    .reduce((p, c, i) => (p[String.fromCharCode(i + 97)] = i, p), {})

console.log(dict)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
1
function range( start, limit ){
    var assoc_array = {};
    var step = 1;
    var DEFAULT_VALUE = "some value";
    step *= limit.charCodeAt(0) - start.charCodeAt(0) > 0 ? 1:-1;
    while( start !== limit ){
        assoc_array[ start ] = DEFAULT_VALUE;
        start = String.fromCharCode(start.charCodeAt(0)+step);
    }
    assoc_array[ limit ] = DEFAULT_VALUE;
    return assoc_array;
}
//Usage examples
var alphabet_array = range('a','z');
var reverse_alphabet_array = range('z','a');

DEMO

Engineer
  • 47,849
  • 12
  • 88
  • 91