Obtain information from a JSON file based on a specific field in Angular

The structure of the JSON file is as follows:

localjson.json
  {
    "Product" :{
           "data" : [
               { "itemID" : "1" , "name" : "Apple" , "qty" : "3" },
               { "itemID" : "2" , "name" : "Banana" , "qty" : "10" } 
      ]

    } }

To retrieve an item by its ID, I have the following function:

       getfruits(itemID: string) {
        return this.http.get<Array<Fruits>>('assets/localjson.json')
            .pipe(
               map((items: Array<any>) => {
              return items.find((item: Fruits) => {
               return item.itemID=== itemID;

             });
           })
              );
             }

Fruits.ts

    export class Fruits{
          itemID: string;
            name: string;
            qty: string;

     }

An error message stating TypeError: items.find is not a function is displayed.

Answer №1

give this a shot

declare interface Food {
  foodID: string;
  type: string;
  quantity: string;
}

getFood(foodID: string) {
 return this.http.get<Array<Food>>('assets/food.json').pipe(
  map((foods: { Menu: { item: Food[] } }) => {
    return foods.Menu[0].find((item: Food) => {
      return item.foodID === foodID;
    });
  })
);

}

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

making a request on an object that includes an array representation of another object

Here is the JSON data I have: [ { "RouteNo": "004", "RouteName": "POWELL/DOWNTOWN/UBC", "Direction": "WEST", "Schedules": [ { "Destination": "UBC", "ExpectedCountdown": -4, }, { "Destination": ...

When making a variable call outside of a subscriber function, the returned value is 'undefined'

I find myself in a situation where I have to assign a value to a variable inside a subscriber function in Angular. The issue is that the variable returns 'undefined' when called outside of the Subscribe function. Here's what I'm encount ...

Memory leakage issues have been reported with the datasnap server method in Delphi XE8

Currently, I am in the process of creating a Datasnap REST server using Delphi. However, I am encountering significant memory leaks. One example is my method station procedure TV1.station(ID: integer); begin GetInvocationMetadata().ResponseContent := ...

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...

Creating a build task in Visual Studio Code with universal TypeScript compiler settings

Our project has the following structure: +-- views +-- viewXXX +-- ts ¦ +-- controller.ts ¦ +-- helper.ts ¦ +-- ... (*.ts) +-- viewXXX.ctrl.js // this is the desired output file +-- viewXXX.c ...

Exploring the JSON Data Structure

Suppose there is a JSON Object let obj = { col1 : 'data' }; The keys 'col1' and the corresponding value 'data' are created dynamically. While it's possible to access 'data' as obj.col1, you're interested ...

Choose the initial selection from a list of changing values using Ionic

I'm having trouble selecting the first option in an Ionic select. I've written a condition based on indexes where if the index is 0, checked should be true, but it's still not working. Here is my code: <ion-item> <ion-l ...

Adding an external JavaScript library file to a specific component in Angular 7 is a straightforward process. Let's walk through the

As a beginner in Angular framework, I've encountered an issue while working on creating a custom HTML template using Angular version 7. My template consists of various pages like home, about, product, etc. Specifically, on the home page, I am trying t ...

Vue.js Element UI dialog box

Is there a method to customize the close button in el-dialog and replace it with my own design? For instance, can I change the default close button located at the top left corner of the dialog? <el-dialog title="Tips" :visible.sync=" ...

Serving sourcemaps for a web extension in Firefox: A step-by-step guide

Currently in the process of developing a web extension using TypeScript, I have encountered an issue with sourcemaps not loading properly. The use of parcel to bundle my extension has made the bundling process simple and straightforward. However, while the ...

Generating Pulumi Outputs for exporting as an external configuration file

I am currently utilizing Cloudrun in GCP and am interested in summarizing the created APIs with API Gateway. To achieve this, a Swagger/OpenAPI v2 document needs to be generated containing the google-generated URLs for the Cloudrun Services. How can I ext ...

Strategies to prevent fortuitous success in testing

I have the following test case: it('is to display a welcome message', () => { spyOnProperty(authServiceSpy, 'token').and.returnValue(environment.testAuthenticationToken); let teacher: Teacher = authServiceSpy.token.teacher; ...

implement some level of control within the ngFor directive in Angular

For instance, let's say I have an ngfor loop: <ng-container *ngFor="let setting of settings | trackBy: trackById"> <button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-me ...

What methods can be used to include optional settings in a custom JsonDotNetResult?

Presented here is an alternative JsonResult, known as the class below, which offers a more advanced JSON serializer compared to the default option for MVC Web Apps (unnecessary details are excluded): public class JsonDotNetResult : JsonResult { public ...

Error: The promise was not caught due to a network issue, resulting in a creation error

I'm trying to use Axios for API communication and I keep encountering this error. Despite researching online and attempting various solutions, I am still unable to resolve the problem. Can someone please assist me? All I want is to be able to click on ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

Guide on updating a table row upon clicking the edit button in an Angular 12 template-driven form

Currently, I have set up a table where the data can be edited by clicking on a hyperlink and then saving the changes with a button. The issue I am facing is that when I click on the edit link, all rows become editable instead of just the specific row I cli ...

The inclusion of a custom list preview with prepare in the sanity schema results in errors during the construction

I recently started working with next.js, TypeScript, and Sanity, and everything has been going smoothly so far. I have multiple schemas defined in my project and it works fine in development. The linting checks also do not show any errors. However, when I ...

What is the process for displaying a String Value on the iPhone 6.0 Simulator after receiving JSON data?

Received the following data from my server: 2014-06-04 13:58:40.201 myRequest[2349:11303] parsing JSON: { "is_vip" = 1; "my_balance" = "1000.21"; "my_name" = "my_foo"; "my_num" = 100; } All values are being printed correctly. However, ...

Enhance user experience by implementing accessibility features in Angular 5 using

Our team is currently working on an Angular 6 application and we need to make it more accessible. I have tried adding aria-live="polite" to our angular-components, but we are experiencing issues with the Chromevox reader interrupting itself during data l ...