4

I am getting the below JSON data from a rest web service. I am trying to figure out how I can convert to an array of object.

{
   "John": "Buttler"
   "Hugh": "Martin"
    .
    .
    .
}

I am trying to convert to below object. Basically I am expecting Person[]. In above JSON, John, Hugh are first names and Buttler, Martin are last names.

export class Person{
    firstName: string;
    lastName: string;
}

I am able to convert if I get the json as below

[
{
   "firstName": "John"
   "lastName:: "Buttler"
},
{
   "firstName": "Hugh"
   "lastName:: "Martin"
}
]

Angular Service Code:

  findAllPersons(): Observable<Person[]> {
    return this.httpClient.get<Person[]>('url');
  }

2 Answers 2

4

You have to process the recieved response in your required format.

      findAllPersons(): Observable<Person[]> {
        return this.httpClient.get<object>('url');
      }
    
    
     findAllPersons().subscribe((response) =>{
        let array = [];
        for(let key in response){
            let p = new Person();
            p.firstName = key;
            p.lastName = response[key];
            array.push(p);
        } 
        console.log(array); // your required array
     });
Sign up to request clarification or add additional context in comments.

Comments

3
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface NameData {
  [firstName: string]: string;
}

interface Person {
  firstName: string;
  lastName: string;
}

@Injectable()
class PersonService {
  constructor(private httpClient: HttpClient) {}

  findAllPersons(): Observable<Person[]> {
    return this.httpClient.get<NameData>('url').pipe(
      map((v) =>
        Object.entries(v).map(([firstName, lastName]) => ({
          firstName,
          lastName,
        }))
      )
    );
  }
}

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.