How i can to convert array to object of array in react?

Viewed 67

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"}
3 Answers

You can do it like this:

let arr = ["Avengers","Batman","Spiderman","IronMan"];
let obj = arr.reduce((acc, item)=> ({...acc, [item]: item}) , {});
console.log(obj);

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);

Related