I have the below json example from my API:
{"Name":"John","Address":"New Town"...} - so the properties like Name and address starts with an upper-case.
I tried to set the return value into the below dto and it does not work. However if I change the name to Name and address to Address, it works. As per my coding convention, I have to use camel case. Is there a way to ignore the case in the mapping?
export interface Employees{
name: string;
address: string;
}
Here is how I do the mapping:
employeeResults: Employees[] = [];
this.employeeService.getEmployeeResults().subscribe((employee: Employees[]) => {
this.employeeResults= hotels;
})
CodePudding user response:
you can use map like this:
this.employeeService.getEmployeeResults().subscribe((employees: any[]) => {
let mappedEmpeloyees = employees.map( (e) => {return {name: e.Name,address:e.Address};})
this.employeeResults= mappedEmpeloyees;
})
CodePudding user response:
As JS is case-sensitive I would suggest using some helper function which can get an object's property by the key in an insensitive way.
const getPopertyByKey = (obj, key) => obj[Object.keys(obj).find(k => k.toLowerCase() === key.toLowerCase())];
And then you can map service's result to your interface:
employeeResults: Employees[] = [];
this.employeeService.getEmployeeResults()
.subscribe((employees: Employees[]) => {
this.employeeResults = employees
.map((e: Employees) => (
{
name: getPopertyByKey(e, 'nAmE'),
address: getPopertyByKey(e, 'AdDrEsS')
} as Employees
)
);
});