1

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;
})
N.F.
  • 3,844
  • 3
  • 22
  • 53
Vida
  • 89
  • 1
  • 8
  • 2
    Would it be an option to handle this on the back-end side? For example say you are using .NET you could use this https://stackoverflow.com/questions/19445730/how-can-i-return-camelcase-json-serialized-by-json-net-from-asp-net-mvc-controll – Mathyn Jan 26 '23 at 08:36

2 Answers2

0

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;
})
0

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
                )
            );
    });
mazooma
  • 116
  • 6