This code snippet is a valuable tool in my current project, allowing me to easily map shortened properties to more readable ones during development. Feel free to use it in your own projects.
(function (angular) {
"use strict";
angular.module("services.mapper", []).service("mapper", [function () {
var models = {
employeeModelContract: {
name_surname: "FullName",
years_of_employment: "YearsOfEmployment"
}
};
return {
map: map,
models: models
}
function map(smallObject, contract) {
var largeObject = {};
for (var smallProperty in contract) {
if (contract.hasOwnProperty(smallProperty)) {
largeObject[contract[smallProperty]] = smallObject[smallProperty];
}
}
return largeObject;
}
}]);
})(angular);
Usage:
var mappedObject = mapper.map(yourJson, mapper.models.employeeModelContract);
UPDATE 1 (Typescript version):
class MapperService implements ng.IServiceProvider {
employeeModelContract:Object= {
name_surname: "FullName",
years_of_employment: "YearsOfEmployment"
};
$get() {
return this;
}
map(smallObject, contract): Object {
var mappedObject: Object = {};
Object.keys(contract).forEach(contractProperty => {
if (contract.hasOwnProperty(contractProperty)) {
mappedObject[contract[contractProperty]] = smallObject[contractProperty];
}
});
return mappedObject;
}
}
class Employee {
constructor(public FullName: string, public YearsOfEmployment: number) { }
}
class Controller implements ng.IController {
constructor(private mapper : MapperService){}
static $inject = ["MapperService"];
json: Object = {
"name_surname": "john_smith",
"years_of_employment": "10"
}
$onInit(): void {
var mapped = <Employee>this.mapper.map(this.json, this.mapper.employeeModelContract);
}
}
angular.module("mapper", []).controller("Controller",Controller).provider("MapperService", MapperService);