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

Angular version 5 and above introduces a new feature called "openFromComponent" within the Snackbar component, facilitating seamless communication

Angular (v5.2.10) Snackbar --| Introduction |-- I am facing a scenario where an Angular component named "Parent" is initializing an Angular Material Snackbar known as snackBar. The snackbar is being passed in the component called SnackbarMessage, which ...

I'm eager to showcase live, incoming data on the chart. However, I'm feeling a bit lost on how to proceed. Can you help

I am currently utilizing the line chart feature of ng2-charts in my Angular project. However, I am unsure how to create a graph with real-time data. Here is an example of some sample data being used for the line chart: lineChartData: ChartDataSets[] = [ { ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Retrieve the object with the JsonPropertyName annotation from an Azure Function

Here is the current structure we are working with: public class Foo { [JsonPropertyName("x")] public string Prop1 { get; set; } [JsonPropertyName("y")] public string Prop2 { get; set; } [JsonPropertyName("z&q ...

Retrieve information prior to CanActivation being invoked

As I develop a web application utilizing REST to retrieve data (using Spring Boot), the server employs cookies for authenticating logged-in users. Upon user signing in, I store their information in the AuthenticationHolderService service (located in root ...

Utilizing Angular Pipes for Utilizing Location

The Location service in Angular is described as "A service that applications can use to interact with a browser's URL." One of its methods, getState(), provides "the current state of the location history," while another method, subscribe(), allows us ...

Allowing Angular2 Components and their Sub Components to access a shared instance of ngModel within a service

Currently, I have been working on constructing a complex view that requires multiple functionalities. To ensure proper organization, I have divided it into various custom components. I don't want to go into great detail, but I have managed to make it ...

Showing information from MySQL database utilizing jQuery and AJAX

Seeking advice as a newcomer trying to create a simple application that utilizes JavaScript, jQuery, and JSON objects to display a MYSQL table. Despite the absence of errors, I am unsure of how to progress with my project. Any insights you can offer would ...

Utilize a external API to fetch JSON data from the website and showcase it on a webpage in a asynchronous manner

<!DOCTYPE html> <html> <head> <script> src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> </head> <body> <input type="text" placeholder="Enter Your Zip Code" id="zipCode ...

What is the best way to create a list of JsonArrays within a JSON file using Java?

I am in the process of compiling a list of banned users and storing it using a json file. To achieve this, I create a JsonArray as shown below: JsonObject json = new JsonObject(); json.addProperty("user", user); json.addProperty("reason", reason); json.add ...

The 'import.meta' meta-property can only be used with the '--module' set to 'es2020', 'esnext', or 'system'.ts(1343)

Whenever I attempt to utilize import.meta.url (as demonstrated in the Parcel docs), I am consistently met with the error message "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es ...

The error message TS2339 in Angular service.component indicates that the property 'subscribe' is not recognized on the type 'Promise<Object>'

Currently, I am in the process of learning Angular by developing a web application for my parish. I have implemented a method for deleting items in the products-list.component.ts file which appears to be technically correct. However, when I attempt to run ...

Retrieving information from a Django model and showcasing it in an HTML table through AJAX

After numerous attempts, I remain unable to successfully display a HTML table using AJAX from a JsonResponse in Django. The closest progress I've made so far is seeing a response in the network console: {"products": "[{\"model\": \"pr ...

Employ jq for extracting rankings from a collection

I need to extract the rankings from a JSON object using only command line tools. The ranking should show the position of each item in its respective category. For instance, let's say I have a file with the following samples: { "category" ...

Error 2322: Troubleshooting Typescript arrow functions overloads issues

Everything seems to be working well with the code below, except for an error that occurs with the resolve constant. const resolve: Resolve Type '(param: "case 1" | "case 2" | "case 3") => boolean | "string" | ...

Using TypeScript to set an HTMLElement in a web page

Currently in the process of transitioning my old JavaScript code to TypeScript. One of the components I have is a Table Of Contents JSX component that helps me navigate easily to specific headings. I had a function that calculated the total offset needed ...

Retrofit encounters a server issue with a 500 Internal Error

I'm facing an issue while trying to update a database record using the Retrofit library. The Postman works fine with the same data. GET request is also functioning properly, but when I try the PATCH operation, it returns an Error 500 Internal Server E ...

Is there a way to create a stub for the given function using sinon?

Here is my test function: const customTestLibrary = require("./test"); describe("Initial Test", function() { it("should run the test function successfully", function(done) { customTestLibrary.execute(); done(); }); }); The te ...

The replaceAll function is not functioning properly when dealing with escape characters in

​ I'm currently working on converting XML data into JSON format using Java. However, I am encountering an error when trying to parse the data. The error is related to a specific character: &#xD; JSON.parse: bad control character in string liter ...

Assistance required for setting a value in a mat-select using Angular

Could really use some assistance resolving the issue with mat-select I'm aiming to establish the initial values by utilizing the following code snippet: orders: Order[] = [{"dish":"steak-0"},{"dish":"tacos-2" ...