Skip to content
-
How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
Last Updated :
07 May, 2024
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);
OutputArray 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);
OutputArray of Objects (using reduce()): [
{ index: 0, value: 'apple' },
{ index: 1, value: 'banana' },
{ index: 2, value: 'cherry' }
]
Similar Reads
How to Convert Array of Objects into Unique Array of Objects in JavaScript ? Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has v
8 min read
How to convert a map to array of objects in JavaScript? A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
How to Convert an Array of Objects to Map in JavaScript? Here are the different methods to convert an array of objects into a Map in JavaScript1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly.JavaScriptcon
3 min read
How to Convert an Object into Array of Objects in JavaScript? Here are the different methods to convert an object into an array of objects in JavaScript1. Using Object.values() methodObject.values() method extracts the property values of an object and returns them as an array, converting the original object into an array of objects.JavaScriptconst a = { java:
3 min read
How to convert a plain object into ES6 Map using JavaScript ? The task is to convert a JavaScript Object into a plain ES6 Map using JavaScript. we're going to discuss a few techniques. To understand the difference between a map and an object please go through the Map vs Object in JavaScript article. Below are the following approaches to converting a plain obje
2 min read
How to convert a Map into a Set in JavaScript? Map and Set in JavaScript are special kind of data structures that holds only the unique data. There will be no duplicate data stored in them. Maps store data in the form of key-value pairs, while the Sets store in the form of values only. In some scenarios, you need to convert a Map into a Set, the
4 min read
How to convert array of strings to array of numbers in JavaScript ? Converting an array of strings to an array of numbers in JavaScript involves transforming each string element into a numerical value. This process ensures that string representations of numbers become usable for mathematical operations, improving data handling and computational accuracy in applicati
4 min read
How to Convert String of Objects to Array in JavaScript ? This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
3 min read
How to Convert Object to Array in JavaScript? In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
4 min read
How to Move a Key in an Array of Objects using JavaScript? The JavaScript array of objects is a type of array that contains JavaScript objects as its elements.You can move or add a key to these types of arrays using the below methods in JavaScript:Table of ContentUsing Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce() met
5 min read
top_of_element && top_of_screen < bottom_of_element) ||
(bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) ||
(top_of_screen > articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}