Pattern Mapper in JavaScript
In JavaScript, the pattern mapper is a design pattern used to map one set of objects to another set of objects using a mapping function. The purpose of this pattern is to simplify the code and make it more modular, by separating the logic of object mapping from the rest of the application.
The pattern mapper typically takes two arrays or objects as input: the source object or array, and a mapping object or array that specifies how the source objects should be mapped to the target objects. The mapping object typically consists of key-value pairs, where the keys represent the property or field names in the source object, and the values represent the property or field names in the target object.
The pattern mapper uses the mapping object to transform the source objects into target objects by iterating over the source object properties and mapping them to the corresponding properties in the target object. The resulting target objects can then be used by the rest of the application.
The pattern mapper can be implemented in various ways, including using built-in JavaScript functions such as map(), reduce(), and forEach(), or using external libraries such as Lodash or Underscore.js.
Here is an example of how the pattern mapper can be used in JavaScript:
Get Dmitriy Belenov’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s say we have an array of source objects that represent books
const books = [
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', year: 1925 },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 },
{ title: '1984', author: 'George Orwell', year: 1949 }
];And we want to map these objects to a new set of objects that only contain the book title and author, and also have a published field that represents the year the book was published. We can create a mapping object like this:
const mapping = {
title: 'title',
author: 'author',
published: 'year'
};Now we can use the mapping object to transform the source objects into target objects using the map() function:
const targetObjects = books.map(book => ({
title: book[mapping.title],
author: book[mapping.author],
published: book[mapping.published]
}));The resulting targetObjects array will look like this:
[
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', published: 1925 },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee', published: 1960 },
{ title: '1984', author: 'George Orwell', published: 1949 }
]This is just a simple example, but the pattern mapper can be used for more complex mappings and with larger sets of data.









