Is there an easy way that I can populate an array with objects containing the identifier and name from A to Z?

Currently my code is doing this:

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

But I need to do this for every character in the alphabet. Is there an easy way I could do this without repeating one character after another in the same way as I did for A and B?

Update

A possible duplicate question does something similar, but does not do what I'm looking for. Hope someone can help with this. Thanks

+4
source share
4 answers

Using map :

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

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

+1
source

( ):

var wordLetterSelect = [];

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

  var letter = String.fromCharCode(i);

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

console.log(wordLetterSelect);

. 65 A, 66 - B... 90 - Z.

+5

use loop.you can create and push objects into an array.

wordLetterSelect = [];
alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
for(var i=0;i<alphabet.length;i++){
    wordLetterSelect.push({id:alphabet[i],name:alphabet[i]});
}
console.log(wordLetterSelect);
+2
source

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>');
Run code
0
source

All Articles