Skip to content

Create map for member: map from

Bert Loedeman edited this page Aug 27, 2015 · 1 revision

mapFrom

A common scenario when performing object-to-object mapping is when source and destination properties are differently named and/or typed. This is the scenario the createMap.forMember.mapFrom function comes to the rescue.

Consider a source object from a REST API with a Person JSON object. The object has a property birthdayString containing the person's birthday in the ISO string notation. The following example taken from the Jasmine unit tests combines the mapFrom function and chaining to map birthdayString to birthday and also convert it to its Date representation.

// arrange
var birthdayString = '2000-01-01T00:00:00.000Z';
var objA = { birthdayString: birthdayString };

var fromKey = '{564F1F57-FD4F-413C-A9D3-4B1C1333A20B}';
var toKey = '{F9F45923-2D13-4EF1-9685-4883AD1D2F98}';

automapper
	.createMap(fromKey, toKey)
	.forMember('birthday', (opts: AutoMapperJs.IMemberConfigurationOptions) => {
                                   opts.mapFrom('birthdayString'); 
                               })
	.forMember('birthday', (opts: AutoMapperJs.IMemberConfigurationOptions) => {
                                   return new Date(opts.destinationPropertyValue); 
                               });

// act
var objB = automapper.map(fromKey, toKey, objA);

// assert
expect(objB.birthday instanceof Date).toBeTruthy();
expect(objB.birthday.toISOString()).toEqual('2000-01-01T00:00:00.000Z');
Clone this wiki locally