Map is an important function which is used to transform data as per our requirement. Suppose we are receiving some data (data can be received either from API or we can use an array value) and we do not want to use the same data but need to modify it before using it in our application. Under this scenario we implement a map in order to modify data as per our need.

  • Map do not change original value, it always creates new value.
  • Map do not work on empty data values.

Below there are some different ways by which we can use map in angular as per the requirements.

1. Using Array Map Method

On Array, Instead of using manually iteration by loop we can simply use built-in Array.map() method.
The Array.map() method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array’s elements.
Now imagine you are required to increment each of the quantity array’s elements by 20. You might consider using a for loop as follows:

Example 1: manipulating array value in normal way:

let quantity = [100,115,90,38,42]
for (let i=0; i<quantity.length;i++)
{    	
     	quantity[i] = quantity[i] +20;
}
console.log (quantity);  // [ 120, 135, 110, 58, 62]

You can directly use Array.map() to achieve the same output.see example below:

let quantity = [100,115,90,38,42];
let updateQuantity = quantity.map(value =>{ return value + 20});
console.log(updateQuantity); // [ 120, 135, 110, 58, 62]

Example 2: transforming array value using map method:

const cart = [5, 15, 25];
let total = 0;
const withTax = cart.map((cost) => {
  total += cost;
  return cost * 1.2;
});
console.log(withTax); // [6, 18, 30]
console.log(total); // 45

The Array.map() method is commonly used to apply some changes to the elements, whether adding/multiplying by a specific number as in the code above, or doing any other operations that you might require for your application.

Use map() over an array of object

Let’s take some example where we need to sum salary and bonus of each element in an array and return the array of totalSalary using array.map().
Example 1: using map method to transform array of object values:

const employees = [
    { name: "Adam", salary: 5000, bonus: 500, tax: 1000 },
    { name: "Noah", salary: 8000, bonus: 1500, tax: 2500 },
    { name: "Fabiano", salary: 1500, bonus: 500, tax: 200 },



    { name: "Alireza", salary: 4500, bonus: 1000, tax: 900 },
];
let newArr = employees.map(item =>{
    item.totalSalary = item.salary + item.bonus;
return item;
});
console.log(newArr);   // [ 5500, 9500, 2000, 5500 ]

Example 2: using map method to transform array of object name values:

let users = [
  {firstName : "Susan", lastName: "Steward"},
  {firstName : "Daniel", lastName: "Longbottom"},
  {firstName : "Jacob", lastName: "Black"}
];
 
let userFullnames = users.map( element =>{
    return `${element.firstName} ${element.lastName}`;
})
 
console.log(userFullnames);
// ["Susan Steward", "Daniel Longbottom", "Jacob Black"]

Using Rxjs Map Operator

Map operator takes an observable source as input. This map operator also works the same as an array map which takes an observable as value and transforms it into a new observable value.
You can use the map operator without using the pipe method if you’re working with RxJS 5 or earlier. Here’s an example of how to do it

const numObs = Observable.from([11, 12, 13, 14, 15]);
const finalObs = numObs.map(val => val * 2);
finalObs.subscribe(res => {
  console.log(`Multiply Number: ${res}`);
});

It is mandatory to use a pipe operator with a map from RxJs 6 or above. Pipe operator allows us to chain multiple operators together.

Example 1: map operator to transform a stream of numbers:

const arr = [1, 2, 3];
const fromArr = from(arr);
fromArr
  .pipe(map((value) => value + 10))
  .subscribe((value) => console.log(`Emitted Values: `, value));

Example 2: Mapping Objects to Specific Properties:

const objectsObservable = from([
  	{ name: 'Alice', age: 30 },
  	{ name: 'Bob', age: 25 },
  	{ name: 'Charlie', age: 35 },
    ]);
    	const namesObservable = objectsObservable.pipe(
  	map((obj:any) => "Mr "+obj.name)
    ).subscribe((name) => {
  	console.log(`Name: ${name}`);
    });

Example 3: filter operator along with the map operator to transform a stream of numbers:

const arrValObs = from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const squaredEvenNumbersObservable = arrValObs.pipe(
  filter((val:number) => val % 2 === 0), // Filter even numbers
  map((evenNumber:number) => evenNumber ** 2) // Square even numbers
).subscribe((squaredEven) => {
  console.log("Squared Even Number:", squaredEven);
});

Support On Demand!

Angular