Instead of manually iterating over the array using a loop, we can use the built-in Array.map() method.
This article will cover map() syntax and how to use map() over an array of objects.
map() is one of the most popular Javascript array methods.
It allows us to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each array’s elements.
map() always returns a new array. It doesn’t change the size of the original array, unlike filter().
The syntax of the forEach() method is:
arr.map(function(currentElement, index, array){ }, this);
For example, we have an array that stores firstName and lastName.
let people = [
{firstName : "Anna", lastName: "Smith"},
{firstName : "John", lastName: "Doe"},
{firstName : "Peter", lastName: "George"}
];
We can use the map() method to iterate over the array and return the combination of firstName and lastName:
let people = [
{firstName : "Anna", lastName: "Smith"},
{firstName : "John", lastName: "Doe"},
{firstName : "Peter", lastName: "George"}
];
let fullNames = people.map(function(item){
return `${item.firstName} ${item.lastName}`;
})
console.log(fullNames);
// ["Anna Smith", "John Doe", "Peter George"]
Logically, map() is quite similar to a for loop.
However, with map(), we don’t need to run a loop to call out each value to add. We need to state what we need and return it.
// using for loop
let arr = [1, 2, 3, 4];
let plus5 = [];
for(let i = 0; i < arr.length; i++) {
plus5[i] = arr[i] + 5;
}
console.log(plus5) // [6, 7, 8, 9]
// using map
let arr = [1,2,3,4];
let plus5 = arr.map((val,i,arr) => {
return val + 5;
});
console.log(plus5) // [6, 7, 8, 9]
The index in the map() method provides the position of each element in an array, but it doesn’t change the original array.
Example
let names = ["Anna", "John", "Peter"];
names.map((name, index) => console.log(`The ${index} is ${name}`));
Output:
The 0 is Anna
The 1 is John
The 2 is Peter
Example 1: Check the object with a condition
In this example, we interact with an array based on a condition.
We check if each object is even or not before we double its value. Initial values in an array that do not satisfy the condition will not change the value.
let arr = [1, 2, 3, 4, 5];
let newArr = arr.map((value, index, arr) => {
return value % 2 === 0 ? value * 2 : value;
});
console.log(newArr);
// [1, 4, 3, 8, 5];
Example 2: Construct a new array of objects
For example, we have an array:
const people = [
{
name: "Anna",
age: 35,
position: "Designer",
},
{
name: "John",
age: 20,
position: "Web developer",
},
{
name: "Peter",
age: 26,
position: "CEO",
},
];
We can construct a new array:
const newPeople = people.map((item) => {
return {
firsName: item.name.toUpperCase(),
oldAge: item.age + 30,
};
});
console.log(newPeople);
// [{firsName: "ANNA", oldAge: 65}, {firsName: "JOHN", oldAge: 50}, {firsName: "PETER", oldAge: 56]