DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Convert Array to Object Keys
Calvin Torra
Calvin Torra

Posted on • Originally published at calvintorra.com

Convert Array to Object Keys

Original Post and more here

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
Enter fullscreen mode Exit fullscreen mode

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: '' }
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Also:

Object.fromEntries(userChoices.map(i=>[i, '']))
Enter fullscreen mode Exit fullscreen mode

Here is a post you might want to check out:

Regex for lazy developers

regex for lazy devs

Sorry for the callout πŸ˜†