3

Currently my code is doing this:

wordLetterSelect = [
    {
        id: 'A',
        name: 'A'
    }, {
        id: 'B',
        name: 'B'
    }
];

But I need to do it for every character in the alphabet. Is there a simple way that I could do this without just repeating one character after the other in the same way as I have done for A and B?

Update

The possible duplicate question does something similar but does not do what I am looking for. Hope someone can help with this. Thanks

Samantha J T Star
  • 28,982
  • 82
  • 233
  • 406

4 Answers4

5

Use this sample (no maps required):

var wordLetterSelect = [];

for (var i = 65; i <= 90; i++) {

  var letter = String.fromCharCode(i);

  wordLetterSelect.push({id: letter, name: letter});
}

console.log(wordLetterSelect);

This code generates an object with letters from their codes. 65 is A, 66 - B ... 90 - Z.

Ali Mamedov
  • 4,748
  • 3
  • 30
  • 43
  • 1
    `String.fromCharCode()` returns a string, you can simply assign to the `letter`, without concatenating – isvforall Apr 30 '16 at 12:51
2

use a loop.you can create and push objects to array.

wordLetterSelect = [];
alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
for(var i=0;i<alphabet.length;i++){
    wordLetterSelect.push({id:alphabet[i],name:alphabet[i]});
}
console.log(wordLetterSelect);
Madhawa Priyashantha
  • 9,427
  • 7
  • 31
  • 59
1

Using map:

var wordLetterSelect = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(function(param){ 
   return {
        id: param,
        name: param
   };
});

Of course you can do the same with a loop if you don't like the map thing.

Andy
  • 53,323
  • 11
  • 64
  • 89
JohnIdol
  • 47,129
  • 60
  • 156
  • 240
0

var getLetter = n => String.fromCharCode(n + 65);

var wordLetterSelect = new Array(26).fill(0).map((_, i) => ({
    id: getLetter(i),
    letter: getLetter(i)
}));

document.write('<pre>' + JSON.stringify(wordLetterSelect, 0, 2) + '</pre>');
isvforall
  • 8,366
  • 6
  • 34
  • 49