An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
December 19, 2021 09:43 am GMT
Original Link: https://dev.to/calvin087/convert-array-to-object-keys-58p3
Convert Array to Object Keys
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 were trying to fill up and return while curr is the current item were working with in the data that were iterating over.
Original Link: https://dev.to/calvin087/convert-array-to-object-keys-58p3
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To