DEV Community

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

Posted on • Originally published at calvintorra.com

3 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Also:

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay