Open In App

How to Convert Array into Array of Objects using map() & reduce() in JavaScript?

Last Updated : 07 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs.

Below are the approaches to convert an array of objects to a map in JavaScript:

Using map()

The array.map() method of JavaScript can be used to iterate through each element of the array and for each element, it creates a new object containing the index and the value of the element thus in the last printing array of objects where each object represents an element of the original array along with its index.

Syntax:

 arrayName.map((element, index, array) => { /* … */ })

Example: The below example is the practical implementation of the map() method to convert an array into an array of objects

JavaScript
const array = ['apple', 'banana', 'cherry'];

// Using map() to convert array into array of objects
const arrayOfObjects = array.map((item, index) => {
    return { index: index, value: item };
});

// Output
console.log("Array of Objects (using map()): ", arrayOfObjects);

Output
Array of Objects (using map()):  [
  { index: 0, value: 'apple' },
  { index: 1, value: 'banana' },
  { index: 2, value: 'cherry' }
]

Using reduce()

The array.reduce() method can be used to reduce an array to a array of objects by passing the initial value as empty array []. After that for each element it creates a new object containing the index and the value of the element, and pushes it to the accumulator array.Thus resultion into an array of objects where each object represents an element of the original array along with its index.

Example: The below code uses the reduce() method to convert array into array of objects

JavaScript
const array = ['apple', 'banana', 'cherry'];

// Using reduce() to convert array into array of objects
const arrayOfObjects = array.reduce((acc, curr, index) => {
    acc.push({ index: index, value: curr });
    return acc;
}, []);

// Output
console.log("Array of Objects (using reduce()): ", arrayOfObjects);

Output
Array of Objects (using reduce()):  [
  { index: 0, value: 'apple' },
  { index: 1, value: 'banana' },
  { index: 2, value: 'cherry' }
]

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads