The following code populates an object called result with the values in keys as the keys and an empty string as each key's value. This is working as desired.
const keys = ['one', 'two', 'three'];
const result = {};
keys.forEach(key => {
result[key] = '';
});
console.log(result);
However, I'm wondering if the result object can be created in a single command by using .map. Below is what I've tried but it yields an array of objects rather than a single object.
const result = keys.map(key => ({
[key]: ''
}));
console.log(result);
You can combine Object.fromEntries and map methods. With map you can get array of [key, value] pairs and then by calling fromEntries you get an object from that array.
const keys = ['one', 'two', 'three'];
const result = Object.fromEntries(keys.map(k => ([k, ''])))
console.log(result)
Here's an alternative approach that only needs one method. (Array.prototype.reduce())
const keys = ["one", "two", "three"];
const result = keys.reduce((a, c) => ({ ...a, [c]: "" }), {});
console.log(result);
you can use your map, then reduce:
keys
.map(k => ({[k]: ""}))
.reduce((x, r) => ({...x, ...r}), {})