Transform array elements into objects JavaScript

Last Updated On Thursday 26th Aug 2021

javascript convert array to object

	const authors = [
  'Jane Austen',
  'William Blake',
  'George Orwell',
];
	

how to convert array to object in javascript

Use loop statements

	const newArray = [];
let counter = 1;
for (let name of authors) {
  newArray.push({
    id: counter,
    name,
  });
  counter += 1;
}
console.log(newArray);
	

No loop statement

Avoid loop statements by using the map methods of the array

	const newArray = authors.map((name, index) => ({
  id: index + 1,
  name
}));

console.log(newArray);
	

References