Home > Enterprise >  How i can to convert array to object of array in react?
How i can to convert array to object of array in react?

Time:12-12

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

CodePudding user response:

You can do it like this:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related