Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Observable map collection of json objects with different property names

I have an json result which is a collection of objects. I need to cast them to a collection of custom objects which have different property names than the json result. Also not all result properties are needed in this instance.

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 for 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 appreciated. Thanks.

like image 242
Brian Avatar asked Feb 15 '17 17:02

Brian


1 Answers

You can map your data to your class like so:

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

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

like image 72
AT82 Avatar answered Sep 30 '22 12:09

AT82