Transforming JavaScript Arrays using map()
Array.prototype.map() method creates and returns a new array with the results of calling a provided function on every element in the calling array.
We can use this method to transform or change elements of an array.
In the following example, we add number 10
to every number in the initial array nums
. The resultant array returned by map()
is stored in the variable newNums
. The original array isn’t modified.
Example
const nums = [2, 4, 6, 8];
const newNums = nums.map(num => num + 10);
for (let num of newNums) {
console.log(num);
}
Output
12
14
16
18
Let us look at another example of using map()
on an array containing objects.
Example
const productsInUSD = [
{ "item": "pen", "price": "2" },
{ "item": "pencil", "price": "1" },
{ "item": "notebook", "price": "3" }
];
const productsInINR = productsInUSD.map(product => {
return {
"item": product.item,
"price": product.price * 75
};
});
for (let product of productsInINR) {
console.log(`${product.item} - Rs.${product.price}`);
}
Output
pen - Rs.150
pencil - Rs.75
notebook - Rs.225
We can also use latest ES6 features and write the map()
method as:
const productsInINR = productsInUSD.map(product => ({
...product,
"price": product.price * 75
}));
Avoid mutating original array
When using map()
on an array of objects, be careful to avoid mutating (modifying) original array and make sure to return a new object from the callback function.
// Don't do this.
const productsInINR = productsInUSD.map(product => {
let newProduct = product;
newProduct.price = product.price * 75;
return newProduct;
});
At first glance, the above code looks good. But we should observe that we are assigning an object reference to newProduct
, therefore modifying newProduct
also modifies the original object.
If we print productsInUSD
array elements to the console, we can see that they are modified and now contain prices in INR. This isn’t desired and breaks functionality in other parts of our application.
To avoid this, clone the object before assigning. There are several ways to clone an object, let us use JSON.parse(JSON.stringify(object))
for this example.
const productsInINR = productsInUSD.map(product => {
let newProduct = JSON.parse(JSON.stringify(product));
newProduct.price = product.price * 75;
return newProduct;
});
This doesn’t modify the original array and prevents any unintended effects.