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.
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);
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.
var hash = {};
hash["abcdefghijklmnopqrstuvwxyz"] = "something";
hash["בגדהוזחטיךכלםמןנסעףפץצקרשת"] = "something else";
hash["АБВГДЕЖЅZЗИІКЛМНОПРСТȢѸФХѾЦЧШЩЪꙐЬѢꙖѤЮѦѪѨѬѠѺѮѰѲѴ"] = "something else";
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]])
}
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)
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.