I need to create an object whose initial state is something like this:
let myDict = {
"A": false,
"B": false,
...
"Z": false
}
But how can I concisely create this in less than 28 lines of code?
Several examples ahead.
Using a custom list of characters:
const myDict = Object.fromEntries([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map(x => [x, false]));
// Test
console.log(myDict);
String.fromCharCode(65) will give you "A" (Wikipedia: ASCII table)
taking that into consideration, you could use 65 + i, where i starts at 0 and ends at 25 (for the 26 characters of the English alphabet).
To keep the code simple here's an example using a for loop:
const myDict = {};
for (let i = 0; i < 26; i++) {
myDict[String.fromCharCode(65 + i)] = false;
}
// Test:
console.log(myDict);
Analogue to the previous, another way would be using Array.prototype.from() to create the character/value entries, and Object.prototype.fromEntries() to convert the array to an Object
const myDict = Object.fromEntries(Array.from({length: 26}, (_, i) => [String.fromCharCode(65 + i), false]));
// Test
console.log(myDict);
Short answer:
const obj = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').reduce(
(obj, char) => {
obj[char] = false;
return obj;
},
{}
);
console.log(obj);
Explanation:
The split method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('') generates an array ["A", "B", ..., "Z"]
The reduce method of Array instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
Applying reduce to generated array ["A", "B", ..., "Z"], generate a single object.
{
"A": false,
"B": false,
...
"Z": false
}
See more:
How to use split?
What does the Array method `reduce` do?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With