Transforming Lists with .map() method in JS

·

2 min read

The “.map” method in Javascript is a transformation operation that modifies an existing array and returns a new array. Let’s imagine the restaurant project that we made would like to display a list of its popular deserts. Remember “list” is a simple collection of elements which is represented as an “array” in JS.

Let’s have a list of its top requested deserts in a variable called “data”. Each desert have the following properties with id,title, image, description and price.

const data = [
{
  "id": 1,
  "title": "Chocolate Cake",
  "image": "https://example.com/chocolate_cake.jpg",
  "description": "A rich and moist chocolate cake topped with ganache and chocolate shavings.",
  "price": 8.99
},

{
  "id": 2,
  "title": "Fruit Tart",
  "image": "https://example.com/fruit_tart.jpg",
  "description": "A buttery tart shell filled with pastry cream and topped with assorted fresh fruits.",
  "price": 6.49
}
,
{
  "id": 3,
  "title": "Vanilla Ice Cream Sundae",
  "image": "https://example.com/ice_cream_sundae.jpg",
  "description": "Creamy vanilla ice cream topped with hot fudge, whipped cream, nuts, and a cherry.",
  "price": 7.99
}

],

In this case, you would like to show a very simple list of desserts with a property called content, which you can create by merging together the title and description and the price of the dish.

First, I’m going to define a new variable since the map method always returns a new array. Let’s call this new array top desserts. Next, I’m going to apply the map method to the original data array.

const TopDeserts = data.map(desert => {
   return;
})

Then I would like the new items to have two properties. The first is content, which is going to be a combination of title and description. Let’s use a dash character to separate the two. Secondly, there’s the price which I will pass as it is.

const TopDeserts = data.map(desert => {
    return{
       content:${dessert.title} - ${desert.description}
        price: dessert.price,
    }
});

Last, I will console log the results to demonstrate that the new list I have created contains the shape or format that I originally intended, and here’s your transformed list.

Chocolate Cake - "A rich and moist chocolate cake topped with ganache and chocolate shavings."......