2

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;
})
1
  • 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 stackoverflow.com/questions/19445730/… Commented Jan 26, 2023 at 8:36

2 Answers 2

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;
})
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.