SK.
SK.

Reputation: 1510

Angular convert json to array of object

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

Upvotes: 4

Views: 8370

Answers (2)

Maroon1
Maroon1

Reputation: 144

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

Upvotes: 3

khush
khush

Reputation: 2791

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

Upvotes: 4

Related Questions