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
  • 30,952
  • 84
  • 245
  • 427

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
  • 5,116
  • 3
  • 33
  • 47
  • 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,633
  • 7
  • 33
  • 60
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
  • 61,948
  • 13
  • 68
  • 95
JohnIdol
  • 48,899
  • 61
  • 158
  • 242
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,768
  • 6
  • 35
  • 50