Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 19, 2021 09:43 am GMT

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

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To