map-factory
A simple utility to map data from an existing object to a new one. This is an alternative interface for the excellent object-mapper.
Map a source field to the same object structure
Mapping is explicit so unmapped fields are discarded.
const createMapper = require("map-factory");
const source = {
"fieldName": "name1",
"fieldId": "123",
"fieldDescription": "description"
};
const map = createMapper(source);
map("fieldName");
map("fieldId");
const result = map.execute();
console.log(result);
Map a source field to a different object structure
Of course, we probably want a different structure for our target object.
const createMapper = require("map-factory");
const source = {
"fieldName": "name1",
"fieldId": "123",
"fieldDescription": "description"
};
const map = createMapper(source);
map("fieldName").to("field.name");
map("fieldId").to("field.id");
const result = map.execute();
console.log(result);
Supports deep references for source and target objects
const createMapper = require("map-factory");
const source = {
"person": {
"name": "John",
"email": "john@someplace.com",
"phone": "(712) 123 4567"
},
"account": {
"id": "abc123",
"entitlements": [{
"id": 1,
"name": "game-1"
},
{
"id": 2,
"name": "game-2"
}]
}
};
const map = createMapper(source);
map("person.email").to("user.login");
map("account.id").to("user.accountId");
map("account.entitlements.[].name").to("user.entitlements");
const result = map.execute();
console.log(result);
You can also reference specific items in an array.
const createMapper = require("map-factory");
const source = {
"articles": [
{
"id": 1,
"title": "Top Article",
"author": "Joe Doe",
"body": "..."
},
{
"id": 2,
"title": "Second Article",
"author": "Joe Doe",
"body": "..."
}
]
};
const map = createMapper(source);
map("articles.[0]").to("topStory");
const result = map.execute();
console.log(result);
More complicated transformations can be handled by providing a function.
const createMapper = require("map-factory");
const source = {
"articles": [
{
"id": 1,
"title": "Top Article",
"author": "Joe Doe",
"body": "..."
},
{
"id": 2,
"title": "Second Article",
"author": "Joe Doe",
"body": "..."
}
]
};
const map = createMapper(source);
map("articles.[0]").to("topStory");
map("articles").to("otherStories", articles => {
articles.shift();
return articles;
});
const result = map.execute();
console.log(result);