2

I have a data in array

["Avengers","Batman","Spiderman","IronMan"]

how I can to covert to below

{"Avenger":"Avenger","Batmane":"Batman","Spiderman":"Spiderman","Ironman":"Ironman"}
devnext
  • 872
  • 1
  • 10
  • 25
  • 1
    Does this answer your question? [Convert Array to Object](https://stackoverflow.com/questions/4215737/convert-array-to-object) – MertHaddad Dec 11 '21 at 18:40

3 Answers3

6

You can do it like this:

let arr = ["Avengers","Batman","Spiderman","IronMan"];
let obj = arr.reduce((acc, item)=> ({...acc, [item]: item}) , {});
console.log(obj);
Saeed Shamloo
  • 6,199
  • 1
  • 7
  • 18
2

Someone else mentioned reduce, but I recommend against, copying objects at every iteration.

Here's a more performant approach.

const arr = ["Avengers","Batman","Spiderman","IronMan"];
const obj = {};

for (const el of arr) {
  obj[el] = el;
}

console.log(obj);
Sal Rahman
  • 4,607
  • 2
  • 30
  • 43
-1

You can use reduce to convert array to object. You can see some examples in here Convert Array to Object