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: '' }
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
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.
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.
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.
try with Array#Reduce
const arr = ['a','b','c']; const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{}); console.log(res)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With