angularangular2-servicesangular2-directivesobject-object-mapping

Object mapping with a defined schema Angular 2/4


I am in a situation where i have to design an object mapper with a defined schema ie I will get a response with an array of objects which is the schema for object mapping like this.

[
{
"fieldToMap":"entityName",
"fieldName":"name"
},
{
"fieldToMap":"entityNumber",
"fieldName":"number"
}
]

When i hit any api endpoint and get the response like this,

[
{
"name":"something",
"number":"something"
},
{
"name":"something",
"number":"something"
}
]

I have to map it to an object and create a nw object like this

[
{
"entityName":"something",
 "entityNumber":"something"
},
{
"entityName":"something",
 "entityNumber":"something"
}
]

How to go about solving this ? Is it good way to loop through the response and replace the keys of the response with the keys presented in the schema or is there any other method which can be used?Any help would be appreciated.Thank you


Solution

  • something like this

    var schema = [
        {
            "fieldToMap":"entityName",
            "fieldName":"name"
        },
        {
            "fieldToMap":"entityNumber",
            "fieldName":"number"
        }
    ]
    
    var response = [
        {
            "name":"something",
            "number":"something"
        },
        {
            "name":"something",
            "number":"something"
        }
    ];
    
    var result = mapObject(response, schema);
    
    function mapObject(data, schema) {
        return data.map(function(el) {
            var obj = {};
            schema.forEach(function(s) {
                obj[s.fieldToMap] = el[s.fieldName];
            });
            return obj
        })
    }