Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to object keys [duplicate]

Tags:

javascript

What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.

['a','b','c'] 

to:

{   a: '',   b: '',   c: '' } 
like image 861
Miguel Stevens Avatar asked Feb 20 '19 15:02

Miguel Stevens


People also ask

Can object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Can an array be a key in an object?

On each iteration, we assign the array value as a key in the object and return the new value of the accumulator variable. We initialized each key to an empty string, however you can assign whatever value suits your use case. The object will contain all of the array's elements as keys after the last iteration.

How do you get keys from array of objects in JS?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.

How do you map an array to an object?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.


2 Answers

try with Array#Reduce

const arr = ['a','b','c']; const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{}); console.log(res)
like image 63
prasanth Avatar answered Sep 23 '22 21:09

prasanth


You can use Array.prototype.reduce()and Computed property names

let arr = ['a','b','c'];  let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});  console.log(obj);
like image 25
Maheer Ali Avatar answered Sep 26 '22 21:09

Maheer Ali