1

I have data in an array:

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

How can I covert it to an object as below?

{"Avenger":"Avenger","Batman":"Batman","Spiderman":"Spiderman","Ironman":"Ironman"}
2

3 Answers 3

5

You can do it like this:

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.