How to transform JSON into an array of objects using Angular

After receiving JSON data from a REST web service, I am exploring ways to convert it into an array of objects.

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

I envision converting it into the following object structure. Essentially, I anticipate an array of Person objects where John and Hugh represent first names, and Buttler and Martin denote last names.

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

If the JSON were structured as:

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

Below is a snippet of the Angular Service Code:

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

Answer №1

Make sure to handle the response you receive in the format that you need.

      getPeople(): Observable<Person[]> {
        return this.apiService.fetchData('url');
      }
    
    
     getPeople().subscribe((response) =>{
        let peopleArray = [];
        for(let key in response){
            let person = new Person();
            person.firstName = key;
            person.lastName = response[key];
            peopleArray.push(person);
        } 
        console.log(peopleArray); // array formatted as required
     });

Answer №2

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

interface NameList {
  [name: string]: string;
}

interface PersonInfo {
  name: string;
  age: number;
}

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

  getAllPersons(): Observable<PersonInfo[]> {
    return this.httpClient.get<NameList>('url').pipe(
      map((data) =>
        Object.entries(data).map(([name, age]) => ({
          name,
          age,
        }))
      )
    );
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Managing an array of categories in each element with rxjs filter: A guide`

I'm in the process of adding a sorting feature to my ionic/angular app. The app pulls vouchers from an API, each belonging to different categories. I need the system to be flexible enough to support multiple categories per voucher. Currently, the solu ...

Dynamic array of fixed-sized arrays

I'm looking to make a member of my class a vector containing std:array, with the size of the array determined by a variable provided by the user. I tried using an initializer list, but encountered this error message: csvParser.cpp:18:35: error: inval ...

What could be the reason for the ERROR message saying, "Cannot read property '0' of undefined"?

I'm really struggling to understand why I keep receiving an Undefined error for tagged_Assets. Can someone please shed some light on this for me? Thank you. Model.ts export class TaggedAssests { device_id: string; hasTag: boolean; } Compon ...

Handling Json responses in Symfony 1.4 with a 404 error

I have been constructing a json api and managing formats through the routing.yml configuration file: user_info: url: /users/:user_id class: sfRequestRoute param: { module: user, action: details, sf_format: json } requirements: user_id: \d ...

Only when your package.json and package-lock.json or npm-shrinkwrap.json files are aligned, can `npm ci` successfully install packages. - Next JS

While attempting to deploy my app on heroku using either heroku cli or github, I encountered the following error: ERROR -----> Installing dependencies Installing node modules npm ERR! code EUSAGE npm ERR! npm ERR! `npm ci` ...

handling text arrays in C for long integers

400000000000;499999999999;VISA; 50000000;59999999;MASTERCARD; 67000000;67999999;MAESTRO; fields: 1. Start Range 2. End Range, 3. Name. "Start Range" and "End Range" fields are allowed to have 1 to 16 characters (digits) in length. The main objective o ...

Angular 2: Finding the object with the highest attribute value in an array of objects

I am currently developing an Angular 2 application and I have an array of objects. My goal is to return the object that has the maximum value of a specific attribute (in this case, the object with the most likes). How can I achieve this in TypeScript? i ...

When trying to ctrl-click on paths in Visual Studio Code, the resolution is incorrect

I'm currently working on customizing a library by modifying its source code. I've downloaded the source code and now I'm trying to configure vscode, typescript, and webpack to recognize that file. Although I've successfully aliased the ...

Creating an npm library using TypeScript model classes: A step-by-step guide

Currently, I am working on a large-scale web application that consists of multiple modules and repositories. Each module is being developed as an individual Angular project. These Angular projects have some shared UI components, services, and models which ...

Guide to modifying the composition of a PHP array

I'm working with an array that has a structure I need to change. This array contains arrays within it, but one of the arrays is always empty and unnecessary for my purposes. I don't need this multilevel array. Here is the current array: array( ...

Tips for executing Angular 7 unit tests using custom environment.test.ts configurations

How can I configure Angular CLI to correctly serve the desired environments/environment*.ts file in Angular 7? Despite attempting to replace the environment.ts with environment.test.ts in multiple locations, I have not been successful. I have tried runni ...

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

Guide on displaying a series of lists in OCaml

Hey there, I'm having trouble printing my list of lists. I've tried multiple methods but just can't seem to find a solution. I attempted to convert my list of lists into an array because I know how to print arrays. I used the function let s ...

How to determine the champion in a game of tic tac toe with the help of Redux and React in

As a beginner in react and redux, I am currently self-studying the concepts. States in my tic-tac-toe project are managed using redux. My goal is to determine the winner when X or O are aligned on the board. Below is my code: // store.ts import { co ...

The mapStateToProps function in a Higher Order Component is receiving an OwnProps argument with a property that is not defined

I'm a new user of react-redux trying to connect a higher-order component to the react-redux store. In the mapStateToProps function, I'm using the ownProps argument to filter the state. However, the property I'm trying to use within OwnProps ...

Transforming Java Web Project into Angular using Java

I'm currently working on a Java web project that uses JSP for the frontend and Java for the backend. I'm looking to convert this project to have an Angular frontend and keep the Java backend. Despite my efforts in searching online, I haven't ...

What is the reason for TypeScript's refusal to accept this task?

In my attempt to create a type that can be A, B, or an object with a key containing an array of 2 or more items that are either A, B, or another similar object (thus allowing for recursive definition). This is the solution I came up with: type A = { p ...

Tips for updating a template dynamically within an Angular 2 and Ionic 2 component

I am working on a component that fetches its template from a remote URL. I am seeking a way to trigger a function upon an event, which will fetch the component's template again and update the already displayed template. @Component({ selector: &ap ...

The data type 'FetchData[]' cannot be assigned to type 'string' in Ionic React with Typescript

How can I store the response.body, which is a base64 string of a file, into a String variable? https://i.sstatic.net/JTkU7C2C.png fetchCustom(store.apiURL, { trtyp: 'file_download', seskey: store.userSessionKey, ...

Traverse an array of nested objects in Firebase JSON notation

Currently, I am utilizing firebase4j, a Java library for Firebase. Although I understand that it is more optimal to use Node.js, I wanted to experiment with Java for this project. Within my database, I am required to store the URLs of images along with var ...