Storing information from JSON into an object

I am encountering an issue regarding transferring data from JSON to an object.

Although this solution is functional, it is not entirely satisfactory. Take a look at the service. Is there an improved method for handling data conversion from this JSON to an object?

The JSON received from the server appears as follows:

{"documents": {"document": [
  {
  "id": 1,
  "description": "Lorem ipsum",
  "date": "2017-03-01"
},{
  "id": 2,
  "description": "Lorem ipsum",
  "date": "2017-04-01"
}
]}}

Here is my service:

 downloadDocuments(id: number): Observable<DocumentsDTO[]>{
   let headers = new Headers();
   headers.append('Content-Type', 'application/json');
   headers.append('Authorization', this.authorizationService.basic);
   let options = new RequestOptions({headers: headers});
   let body = JSON.stringify(id);
   return this.http
     .post(DOCUMENTS_URL, body, options)
     .map((response) => response.json().documents.document)
 }

Below is the component where I invoke this service:

documentsArray: Array<DocumentsDTO>;

downloadUserDocuments(id: number) {
   this.documentsService.downloadDocuments(id)
     .subscribe(documents =>{
       if(documents !=null){
         this.documentsArray = [];
         documents.forEach((data) => {
           this.documentsArray.push(data);
         });
       }
     });
 }

While this approach serves its purpose, I believe there may be room for improvement in terms of converting this JSON to an array. Any suggestions for enhancing this process?

Answer №1

Assistance

using this.http
  .post(DOCUMENTS_URL, body, options)
  .map((res: Response) => {
    res.json().map((obj) => {
      new Document(obj.id, obj.description, obj.date)
    })
  })

The output should be a group of Documents

Answer №2

I don't see a way around the issue

.map((response) => response.json().documents.document)

The array is directly nested inside the response, so changing this would require modifications to the backend.

What puzzles me is the unnecessary iteration within your subscribe function. Why not simply assign the incoming array to documentsArray directly like this:

this.documentsService.downloadDocuments(id)
  .subscribe(documents => {
     if (documents != null) {
       this.documentsArray = documents;
    }
 });

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

TypeScript: The capability to deduce or derive values for a type from a constant object literal that is nested with non-distinct keys

I'm trying to figure out a way to utilize TS/IDE to display specific literal values from a style guide object, instead of just the inferred type. Here's an example: const guide = { colors: { black: { medium: "#000000", } ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

Obtaining details of a node-mysql error

Whenever there is an issue with my query or connection, I receive the following error message: { [Error: ER_DUP_ENTRY: Duplicate entry '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d2def3cb 5dadfd6c09dd0dcde">[e ...

"Encountering a 404 error with the angular2-in-memory-web-api

Currently, I am in the process of developing a 5 minute application using Angular 2 with reference to this particular guide: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html. While working on the HTTP section, I encountered a 404 error due to the a ...

Angular 2's Http Post function mistakenly triggers dual ajax requests instead of a single one

Greetings! I have been delving into the implementation of the observable pattern in Angular and seem to be facing some issues. Below is the code snippet that is causing trouble: import 'rxjs/Rx'; import {Injectable, EventEmitter} from 'ang ...

The API call is failing when using getInitialProps in Next.js

I have been trying to retrieve data from an API using the getinitialprops method and axios However, it seems like my code is not working as expected. Here is a snippet of the relevant code in the file pages/index.tsx IndexPage.getInitialProps = async (ctx ...

Obtain the values from this JSON array

o = { "photos": { "page": 1, "pages": 46, "perpage": 5, "total": "230", "photo": [{ "id": "6643924777", "owner": "34653895@N08", "secret": "3b7c2f6469", "server": " ...

Guide on transferring JSON data to a PHP script by utilizing jQuery's submit function

Hey there, I am just starting to explore JSON in jQuery. I have created an HTML form using JSON data and JavaScript, where the JSON string holds the result. My question is how do I send this string to a PHP file? I am currently using an ajax function to ...

The file or assembly 'Newtonsoft.Json' with the version 8.0.0.0, culture neutral, and public key token 30ad4fe6b2a6aeed could not be loaded

I recently added the Newtonsoft.Json NuGet package to my project. Unfortunately, I encountered the following error: An issue occurred while trying to load the file or assembly 'Newtonsoft.Json' with Version=8.0.0.0, Culture=neutral, PublicKey ...

Ruby Stateful JSON Parsing Tool

I am currently working with a Ruby server that is continuously reading from a flat file which gets updated every second by another server. This flat file is in JSON format, and I want the server to only read the new data instead of parsing the entire fil ...

Using Google's Closure Compiler to Optimize JSON Files

When dealing with a json string that is parsed and properties of the object are accessed using dot notation, a warning may be triggered by the google closure compiler stating that the property is not defined. To overcome this issue, one workaround is to c ...

Retrieve individual item

It has been a few days since I started working on this. I am attempting to create a query that retrieves all businesses registered in a specific city. Subsequently, for each business, I aim to fetch all products associated with that business and then cons ...

The object literal is restricted to defining existing properties, and 'id' is not a recognized property in the type 'FindOptionsWhere<Teacher>'

I encountered a persistent error within my teachers.service: Object literal may only specify known properties, and 'id' does not exist in type 'FindOptionsWhere | FindOptionsWhere[]'.ts(2353) FindOneOptions.d.ts(23, 5): The expected t ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

Looking to verify the functionality of the router.navigate method when employing relativeTo?

How can we effectively test the router.navigate method to ensure it accepts provided queryParams and navigates to the correct location path? In Component file:-- syncQueryParams() { this.router.navigate([], { relativeTo: this.activatedRoute, ...

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

Organize library files into a build directory using yarn workspaces and typescript

When setting up my project, I decided to create a yarn workspace along with typescript. Within this workspace, I have three folders each with their own package.json /api /client /lib The main goal is to facilitate code sharing between the lib folder and b ...

Convert an array with three dimensions into a two-dimensional array that includes tuples with two immutable string values

Consider the array below with multiple dimensions: type ParsedLine = [string, string]; type ParsedLines = [ParsedLine, ParsedLine] const myArray: (ParsedLine | ParsedLines)[] = [ ['something', 'somethingElse'], [['foo', & ...

problem encountered when running "ionic cordova build android --prod --release"

A chat application has been developed using Ionic2. Upon attempting to generate a production build with ionic cordova build android --prod --release, the following error is encountered. Error: ./node_modules/rxjs/observable/BoundCallbackObservable.js ...