Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows:

[
    {
        "documents": [
            {
                "title": "+1 (film)",
                "is-saved": false,
                "abstract": "some text",
                "id": "_1__film_",
                "url": "some url"
            }
        ]
    }
]

Each element in the array represents a Result.

While I understand how to map one Result, here's an example:

static resultFromJSON(json): Result {
    let documents: SearchQueryDocument[] =
        json.documents.map(doc => new SearchQueryDocument(doc.title, doc.issaved, doc.abstract, doc.id, doc.url))
        return new Result(documents)
}

However, I'm struggling with mapping the entire array. How can I achieve this?

static resultsFromJSON(json): Result[] {
    let results: Result =
    json.map ... // what should go here? 
}

Mapping one result using json.documents.map... is straightforward, but when it comes to mapping the whole array, I'm stuck.

I may be a newbie asking a seemingly simple question, but any guidance would be greatly appreciated!

Answer №1

If I am understanding correctly, the JSON you have corresponds to the following interfaces:

interface IDocument {
    title: string;
    "is-saved": boolean;
    "abstract": string;
    id: string;
    url: string;
}

interface IResult {
    documents: Document[];
}

It seems like you have an array of Result.
To map that JSON, you can use the following method:

static resultsFromJSON(json): Result[] {
    return json.map(obj => {
        new Result(obj.documents.map(doc => {
            return new SearchQueryDocument(doc.title, doc.issaved, doc.abstract, doc.id, doc.url);
        }));
    });
}

Answer №2

The solution that successfully resolved my issue involved making a minor adjustment to the static method originally proposed by Nitzan Tomer.

Here is the modified code snippet:

static resultsFromJSON(parsedData): Result[] {
    return parsedData.map(object => 
        new Result(object.documents.map(document => 
            new SearchQueryDocument(document.title, document.isSaved, document.abstractText, document.id, document.url)
        ))
    )
}

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

Implementing JSON parsing in an ESP32 application using AJAX script

Currently, I am engrossed in a project that involves utilizing ESP32. I'm obtaining data from various sensors and transmitting it to a webpage hosted on the same board. After doing some research online, I learned that it's considered "better" to ...

Is Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

Camera Capacitor designed to eliminate popup notifications

I am utilizing Angular along with the camera plugin in Capacitor to locally save images on both desktop and tablets. I aim to utilize the CameraSource to directly access the camera or open the gallery for files without displaying a prompt. This is how my ...

Arranging JSON array in Angular 6 by specific key within the nested array

Is there a way to sort the data object based on the order numbers inside the array objects? data =[ { name:'' list:{ order :2 }, { name:'' list:{ order :1 } ] ...

Can parameters with identical union types in a function signature be streamlined to contain only the exact same subtypes using generic types?

// defining a type Combinable with string or number as possible values type Combinable = string | number; // function to check if parameter is a string function isString(param: unknown): param is string { return typeof param === "string"; } /** * Func ...

Using ngIf in Angular and eliminating components in Angular 6

Currently, I am faced with the challenge of removing the header and footer components in one specific component, but I'm unsure about how to proceed. In my approach, I consider the app component as the index.html component. Whenever I create a new com ...

Develop an Angular application with a customized URL path that utilizes a ServiceWorker

I am currently working on an Angular 10 application. It utilizes the Angular "service worker" to transform into a PWA. Once the app is compiled, it resides in "c:\-website-folder-\ng-app\dist". Users can access the app through a URL like: ...

Are there more efficient alternatives to utilizing arrays and index-based functions for storing in-memory data in TypeScript?

Is there a more efficient method for storing and retrieving data besides relying on Array index-based calls? For instance: export interface EntityInterface { id: number; name: string; age: number; } export class ClassName { entities: Enti ...

Subscribing with multiple parameters in RxJS

I am facing a dilemma with two observables that I need to combine and use in subscribe, where I want the flexibility to either use both arguments or only one. I have experimented with .ForkJoin, .merge, .concat but haven't been able to achieve the des ...

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...

Issue with passing parameters to function when calling NodeJS Mocha

I have the following function: export function ensurePathFormat(filePath: string, test = false) { console.log(test); if (!filePath || filePath === '') { if (test) { throw new Error('Invalid or empty path provided'); } ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

Updating *ngIf in Angular 6 after the Component has finished Loading

Component: import { Component, OnInit } from '@angular/core'; // Services import { AuthService } from './services/auth.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleU ...

What methods can be used to monitor changes made to thumbnails on the YouTube platform?

I have embarked on a project to create a Chrome extension that alters the information displayed on the thumbnails of YouTube's recommended videos. In this case, I am looking to replace the video length with the name of the channel. Imagine you are on ...

Display identical text using JavaScript filter

My search filter highlight is currently displaying [object Object] instead of <mark>match values</mark> when replacing the values. This is the code I am using: this.countries.response.filter((val) => { const position = val.value.toLowerCa ...

How can HostBinding be used to target a custom directive in order to deliver either a success or error message and show it on

I am incorporating a custom directive to display specific server messages/errors following an http request. For example, in the response or error section, I want to target the custom directive and present the emphasized message. The directive is already e ...

Transforming file location to base64 encoded format using TypeScript

I have the path of an image and need to convert it to base64 format, similar to this data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUg... function encodeImageToBase64(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { va ...

Determining the inner type of a generic type in Typescript

Is there a way to retrieve the inner type of a generic type in Typescript, specifically T of myType<T>? Take this example: export class MyClass { myMethod(): Observable<{ prop1: string, ... }> { .... } } type myClassReturn = ReturnTy ...

Encountered a NullPointerException while attempting to generate an array from a MySQL database

I encountered a NullPointerException while attempting to create a multiple array of data from MySQL. The error seems to be originating at this line of code: JSONObject jsonResponse = new JSONObject... NewsFeed.java public class NewsFeed extends Fragment ...

Navigating using ViewChild in Ionic 2 Beta

I recently updated my Ionic 2 app to use Angular 2 RC1, which has been a great improvement. However, I am facing some challenges with the routing implementation. Despite following the update guide, I still encounter issues with my navigation component bein ...