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.

2
  • 3
    So what is your question? What did you try? Commented May 16, 2012 at 11:02
  • Martin - In PHP, this can be done easily by using range function as in range('a','z'), and I wanted to know if there's a similar smart way of doing it in JavaScript. Thanks. Commented May 16, 2012 at 11:07

7 Answers 7

13

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/

Sign up to request clarification or add additional context in comments.

2 Comments

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 stackoverflow.com/a/9878531/684932 to do so and works like a charm.
This is awesome
4
var hash = {};
hash["abcdefghijklmnopqrstuvwxyz"] = "something";
hash["בגדהוזחטיךכלםמןנסעףפץצקרשת"] = "something else";
hash["АБВГДЕЖЅZЗИІКЛМНОПРСТȢѸФХѾЦЧШЩЪꙐЬѢꙖѤЮѦѪѨѬѠѺѮѰѲѴ"] = "something else";

2 Comments

Thanks Andrew. I am looking for something like this - obj[a] = 'somevalue', obj[b] = 'somevalue' and so on until obj[z]= 'some value'.
you did ask for "alphabets" :P
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.

5 Comments

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').
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.
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?")
Agreed. I have updated my answer to use the preferred syntax.
Thanks for your inputs. I am looking for something similar to Thack_Mai and Jake's solution.
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]])
}

1 Comment

Explain the magic numbers 65 and 90 (e.g. by const declarations or similar).
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)

Comments

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

Comments

0

console.group("Alphabets form (A-Z) are:");
var a = 65;
for (var i = 0; i<26; i++) { 
    console.log(String.fromCharCode(a + i))
}
console.groupEnd();

console.group("Alphabets form (a-z) are:");
var a = 97;
for (var i = 0; i<26; i++) { 
    console.log(String.fromCharCode(a + i))
}
console.groupEnd();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.