Convert Array to Object in JavaScript?

I am trying to convert array to objects .

let arr = ["value1","value2"]

My trying code is :


expected Output :

  {value1:{},value2:{} }

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can try with .forEach() as the following:

const arr = ["value1", "value2"];
const result = {};

arr.forEach(e => result[e] = {});


Solution 2

You could take Object.fromEntries and map the wanted keys with empty objects.

let keys = ["value1", "value2"],
    object = Object.fromEntries( => [key, {}]));


Solution 3

Use array reduce!

arr.reduce((accumulator, value) => ({ ...accumulator, [value]: {} }), {});

Solution 4

You can use .reduce() to get the desired output:

const data = ["value1", "value2"];

const result = data.reduce((r, k) => (r[k] = {}, r), {});


Solution 5

There’s also Object.fromEntries method specifically designed to convert an array of entries (key-value tuples) to an Object.

let arr = ['value1', 'value2'];
let entries = => [el, {}]);
let obj = Object.fromEntries(entries);


Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply