I wanted to take an array of elements and turn them into an object. The elements in the array would need to be the keys of the object with some default empty strings as the values to be changed later.
['name','age','city', 'town', 'country']
{
name: "",
age: "",
city: "",
town: "",
country: ""
}
// end result I was looking for
In the end I discovered that we could use Array.reduce (which I used to avoid before learning how to use it).
We can create an empty object, pass over the array items and use them to dynamically create object keys.
const userChoices = ['name','age','city', 'town', 'country'];
const result = userChoices.reduce((acc, curr) => {
acc[curr] = ""
return acc
}, {})
result.name = "calvin"
console.log(result)
// { name: 'calvin', age: '', city: '', town: '', country: '' }
The empty object is used as the accumulator which is passed back into the function and filled with the next item in the array.
acc is the thing weβre trying to fill up and return while curr is the current item weβre working with in the data that weβre iterating over.
Top comments (1)
Also: