How To Rename Field From Object
I'm using Angular 5. I have 'fake back-end' (array of items). My case: I'm waiting for the following structure of object: id: number, title: string But, Back-End sends me wrong st
Solution 1:
Good practice on large apps where you don't have much control over the backend is to create a mapper for each response type you expect.
For example you make an http request to retrieve a list of cars from your backend. When you retrieve the response, you pass the data to a specific mapping function.
classCarMapper {
// map API to APPpublicserverModelToClientModel(apiModel: CarApiModel): CarAppModel {const appModel = newCarAppModel(); // your Car constructor// map each property
appModel.id = apiModel.id_server;
appModel.name = apiModel.title;
return appModel; // and return YOUR model
}
}
This way on the client side you always have the correct data model. And you adapt on any model change made on the backend.
Solution 2:
You can check if an object has name key and then create another object with title
if (obj.hasOwnProperty("name")){
var newObj = {
id: obj.id,
title: obj.name
};
}
obj = newObj;
Post a Comment for "How To Rename Field From Object"