How an observable collection of json object maps with different property names

I have a json result, which is a collection of objects. I need to send them to a collection of custom objects that have different property names than the json result. Also, not all properties of the result are necessary in this case.

Json

[{"empID":"12345", "formattedName":"Simpson, Homer"}, {"empID":"24680", "formattedName":"Simpson, Marge"}, {"empID":"36912", "formattedName":"Simpson, Bart"}, {"empID":"13579", "formattedName":"Simpson, Lisa"}, {"empID":"13579", "formattedName":"Simpson, Lisa"}] 

My custom ojbect

 export class multiSelect { constructor( public id: string, public name: string ) { } } 

Service

  reportsTo(): Observable<multiSelect> { return this._http.get('getCollection') .map((response: Response) => response.json()) .map(({empID, formattedName}) => new multiSelect(empID, formattedName)) .catch(this.handleError); } 

I would like my service to return this

 [{"id":"12345", "name":"Simpson, Homer"}, {"id":"24680", "name":"Simpson, Marge"}, {"id":"36912", "name":"Simpson, Bart"}, {"id":"13579", "name":"Simpson, Lisa"}, {"id":"13579", "name":"Simpson, Lisa"}] 

Any help would be greatly appreciated. Thanks.

+5
source share
3 answers

You can match your data with your class as follows:

 reportsTo() { return this._http.get('getCollection') .map((response: Response) => response.json().map(res => new multiSelect(res.empID, res.formattedName))) .catch(this.handleError); } 

This should do what you want. Hope this helps! :)

+1
source

I suggest creating a method in the multiSelect class:

 export class multiSelect { constructor( public id: string, public name: string ) { } fillWithData(data){ //this function receive your json this.id = data.empID; this.name = data.formattedName; } } 

Then a JSON.strigify(multiSelectInstance) will do the trick.

If you want to use the constructor, so you only need one call, you can do the following:

 export class multiSelect { constructor( public id: string, public name: string, public data ) { this.id = data.empID; this.name = data.formattedName; } fillWithData(data){ //this function receive your json this.id = data.empID; this.name = data.formattedName; } } 
0
source

It may be easier for you to change your service to something like this:

 reportsTo(): Observable<multiSelect> { return this._http.get('getCollection') .map((response: Response) => response.json()) .map(({empID, formattedName}) => ({id: empID, name: formattedName})) .catch(this.handleError); } 

Then get rid of your multiSelect class and replace it with an interface.

 export interface multiSelect { id: string; name: string; } 

Typescript will ensure that the returned observable has data in the correct format due to the interface, and now you do not need to deal with classes or constructors.

0
source

Source: https://habr.com/ru/post/1264261/


All Articles