TypeScript library for mapping objects and classes.
Installation:
npm i flex-mapper
Maps objects
import { map } from 'flex-mapper';
...
const cat = {
name: "Tom",
color: "gray",
years: 2
}
const result = map(cat, {
name: 'nickname',
color: value => value.toUpperCase(),
years: [value => value * 12, "months"]
});
console.info(result);
// {
// nickname: "Tom",
// color: "GRAY",
// months: 24
// }
Destination class definition. Mapping options are described with decorators: @mapProperty
and @mapConvert
.
import { mapProperty, mapConvert } from 'flex-mapper';
...
class CatClass {
@mapProperty("name")
nickname: number;
@mapConvert(value => value.toUpperCase())
color: string;
@mapProperty("years", value => value * 12)
months: number;
}
Mapping class object:
import { map } from 'flex-mapper';
...
const cat = {
name: "Tom",
color: "gray",
years: 2
}
const result = map(cat, CatClass);
console.info(result);
// {
// nickname: "Tom",
// color: "GRAY",
// months: 24
// }
This is important to pass the class type as a second parameter. In this way map
method reads decorators defined inside the class.
Describes how the property is to be mapped.
Parameter is an interface with properties:
Name | Type | Description |
---|---|---|
source | string |
Source property name |
convert |
function or string
|
In function case, parameter is source value the function result is definition value. In string case, possible values are: number , string . |
Has one function
or string
parameter for converting.