Convert Array to Object in JavaScript?

I am trying to convert array to objects .

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

My trying code is :

 Object.assign({},arr)

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] = {});

console.log(result);

Solution 2

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

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

console.log(object);

Solution 3

Use array reduce!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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), {});

console.log(result);

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 = arr.map(el => [el, {}]);
let obj = Object.fromEntries(entries);

console.log(obj);

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

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

Leave a Reply