Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects.

Here is the response retrieved from the API:

{
    "criteria": {
        "requirePictures": true,
        "q": null,
        "allowedIngredient": null,
        "excludedIngredient": null
    },
    "matches": [
        {
            "imageUrlsBySize": {
                "90": "https://lh3.googleusercontent.com/8H_kR4fF6IE517FKDHGOyVHEgNmmCdhX_Yz2YfxIDJgCQoU_NJ-hw_FJ1jEolQPPAfoKuKMw4jYjJK512gTyfQ=s90-c"
            },
            "sourceDisplayName": "Mrs. Happy Homemaker",
            "ingredients": [
                "frozen meatballs",
                "pasta sauce",
                "shredded mozzarella cheese",
                "shredded parmesan cheese",
                "Italian seasoning"
            ],
            "id": "Meatball-Parmesan-Casserole-2626493",
            "smallImageUrls": [
                "https://lh3.googleusercontent.com/3dbNmfS4BI-7CUsm2WYE8l7-90CNi3rQPUkO5EMc0gts_MBUAVZlTngm-9VHshp9toXl73RKwiUs9JQCpx6RoQ=s90"
            ],
            "recipeName": "Meatball Parmesan Casserole",
            "totalTimeInSeconds": 900,
            "attributes": {
                "course": [
                    "Main Dishes"
                ]
            },
            "flavors": null,
            "rating": 4
        }
    ],
    "facetCounts": {},
    "totalMatchCount": 1228808,
    "attribution": {
        "html": "Recipe search powered by <a href='http://www.yummly.co/recipes'><img alt='Yummly' src='https://static.yummly.co/api-logo.png'/></a>",
        "url": "http://www.yummly.co/recipes/",
        "text": "Recipe search powered by Yummly",
        "logo": "https://static.yummly.co/api-logo.png"
    }
}

I am attempting to tackle this issue using the map operator in my code snippet below.

  list(): Observable<Recipe[]> {
    return this.http.get('url').pipe(
      map(data =>
        data.matches.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

However, I encountered an error stating that "matches does not exist on type Object". Am I overlooking something crucial? How can I effectively access the "matches" array to instantiate Recipe objects dynamically within an array? Also, should I stick with utilizing the map operator or explore alternative approaches?

Answer №1

  fetchData(): Observable<any> {
    return this.http.get('url').pipe(
      map(data =>
        data.matches.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

Alternatively

fetchData(): Observable<Recipe> {
    return this.http.get('url').pipe(
      map(data =>
        data.matches.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

Consider implementing one of these solutions, since you are receiving a single JSON object from the URL but providing an array of objects in observables.

Answer №2

To resolve the issue, I decided to replace it with the following solution:

list(): Observable<Recipe[]> {
    return this.http.get('url').pipe(
      map((data: any) =>
        data.matches.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

I made an adjustment of changing 'data' to '(data: any)'

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

What is the process for executing JavaScript code that is stored as a string?

After making an AJAX call, I receive a random string (constructed dynamically on the server) that contains JavaScript code like: Plugins.add('test', function() { return { html: '<div>test</div&g ...

A useful tip for emphasizing tags that have attributes with endings

Here is the HTML list I'm working with: <li class=​"info" data-info=​"" data-title=​"info 1" data-info-id=​"222643">…</li> <li class=​"info" data-info=​"" data-title=​"info 2" data-info-id=​"217145">…</li> ...

The issue arises when attempting to drop elements from two lists with incorrect positions and mismatched coordinates

Angular 9 had a working version of this, which you can find here: https://stackblitz.com/edit/two-drop-list-problem-zp556d?file=package.json Now in the new Angular 14 version: https://stackblitz.com/edit/angular-ivy-1jvbnn?file=src%2Fapp%2Fapp.component ...

Exporting a module from a TypeScript definition file allows for seamless sharing

I am in the process of developing a definition file for the Vogels library, which serves as a wrapper for the AWS SDK and includes a property that exports the entire AWS SDK. declare module "vogels" { import AWS = require('aws-sdk'); export ...

Trigger the opening of a class or window upon pressing the button

Good evening, I'm attempting to create a functionality where pressing a specific button will open a window. However, I am unsure of how to achieve this using CSS classes. My initial thought was to add a new class in the CSS file and call it every ti ...

What is the best way to permit multiple instances of a component in separate tabs without losing their individual states?

My application is equipped with a lazy loading tab system that is controlled by a service. When a user chooses an option from the navigation menu, two key actions take place : An entry is appended to the tabs array within the tab service. A new route is t ...

Is there a way for me to retrieve the element that is linked to the ng-disabled attribute?

Is there a way to access the element with the ng-disabled attribute inside the function without passing it as a parameter? Here is the HTML element: <input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text"> The isFieldDisabled fu ...

Struggling to remove the image tag from the jQuery ajax response

My web app is designed to send an ajax post request to a PHP script, which then returns a chunk of HTML data. This HTML includes an image and a table of information. The challenge I'm facing is how to extract the image from the rest of the HTML so tha ...

The Angular2 Mvc5 demonstration application is experiencing compilation errors

I recently started using Visual Studio Enterprise 2015 Update 3 and decided to create a new project called "Angular2 Mvc5 sample application" from the templates available online. However, upon compiling the project, I encountered numerous errors such as: ...

Blend jQuery fade in

I have two variables var $aa = $('#Adiv').find('li').has('class'); var $bb = $('#Bdiv'); Both variables should be faded in using fadeIn() $aa.fadeIn(); $bb.fadeIn(); If they have the same action, is it possible ...

One controller, divergent template, introducing a fresh variable

I have a webpage where I showcase data (www.mysite.com/:gameId). In order to create a printer-friendly version of this data, I've set up a print page at www.mysite.com/:gameId/print. Both pages display the same information but with different designs. ...

Discovering the RGB color of a pixel while hovering the mouse in MapboxGL Js

Looking to retrieve the RGB color value of the pixel under the mouse hover in MapboxGL Js. What is the most effective method to accomplish this task? ...

Create and transmit an array of JSON objects

I need help with defining and sending a JSON object array. While I've managed to define a single JSON object, convert it into a string, and send it, I'm stuck on how to do the same for an array of objects. It seems like there might be a simple so ...

Personalized Jasmine matchers for a Protractor/WebDriverJS component

Greetings fellow developers, I'm looking to create a custom matcher for Protractor/WebDriverJS element. Can anyone assist in improving my current code? Here is what I aim to include in the specs files: var button = element(by.tagName('button&a ...

JavaScript's version of "a certain phrase within a text"

If I'm working in Python and need to verify if a certain value is present in a string, I would use: if "bar" in someString: ... What would be the equivalent code in Javascript for this task? ...

Middleware functions in Mongoose for pre and post actions are not being triggered when attempting to save

After carefully reviewing the documentation, I am still unable to pinpoint the issue. The pre & post middleware functions do not appear to be functioning as expected. I have made sure to update both my node version and all modules. // schema.js const sch ...

Leveraging AJAX to transmit a JavaScript variable to PHP within the same webpage

I have a webpage where I want to update a PHP variable based on the value of a name attribute when a user clicks on a link. Here is an example of what I am attempting to accomplish: // PHP <?php $jsVar = $_POST['jsVar']; echo $jsVar; ...

Chrome causing window.open to fail

I am currently working on developing a Cordova PhoneGap app and facing an issue with popping up a window for Facebook login after clicking a button. The popup works fine on iOS devices, but when I try debugging with Chrome, nothing happens even though th ...

How to retrieve data from an undefined table using Sequelize that is created through association

I've encountered a new challenge while working on my latest project; Imagine the tables User and Project in Sequelize have been defined. There's also a third table in the database called ProjectsUsers, and I need to retrieve data from there. T ...

What could be causing BeautifulSoup to overlook certain elements on the page?

For practice, I am in the process of developing an Instagram web scraper. To handle dynamic webpages, I have opted to utilize Selenium. The webpage is loaded using: driver.execute_script("return document.documentElement.outerHTML") (Using this javascript ...