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

Organizing files in an ExpressJs project with Angular2

What is the conventional file structure for a mix of ExpressJs and Angular2 projects? Here's my current setup: Project | |--bin |--node_modules |--public |--images |--javascripts |--stylesheets |--routes |--views |--app.js |-- ...

The 405 method not allowed error pops up when trying to use Ajax Delete immediately after

I encountered an issue while trying to remove a vehicle from the table. Everything was working fine on my localhost (Visual Studio), but when I published the project, I started getting a 405 Method Not Allowed error. http://localhost:41904/api/vehicles/42 ...

Setting up Angular 2 for ASP.NET MVC: A Step-by-Step Guide

angular.io provides a setup guide for asp.net core at: https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html. However, I am trying to configure it for an asp.net mvc application. The Quick Start files are already present in the asp.net mvc te ...

Discovering JSON data embedded within a script tag in an HTML response using Jsoup

Looking for help with extracting JSON content from script tags embedded in an HTML file. I attempted to use Jsoup without success. Can anyone provide guidance on utilizing JSOUP or another library for this task? Thank you in advance. ...

Angular makes it easy to extract multiple parameters from a URL

In the process of developing a basic Angular application using TypeScript, I have encountered an issue. Within my project, there is a URL structure like this: www.example.com/api/1/countries/Italy/ My goal is to extract the values 1 and Italy from this U ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

The attribute 'do' is not defined in the AngularFireList type

Despite coming across numerous similar posts, I am still struggling to comprehend the issue at hand and how to resolve it. posts$: Observable<Post[]> = this.db .list(`posts/${this.uid}`) .do(next => this.store.set('posts', next) ...

Using React with Typescript involves using the React.createElement method

I am facing an issue with a reference to a FunctionalComponent in my object. When I try to pass this reference into the createElement statement, it triggers a TypeScript error. Question: Why is this error occurring? Both Component and FunctionalComponent ...

A guide on harnessing the power of Jest when integrating it with vuex-module-decor

In my Typescript-written Vue component, I am facing an issue while trying to write a unit test using vue-test-utils and jest. The problem arises when injecting the vuex store that was created with vuex-module-decorators. Below is a snippet from my Vue com ...

How to Implement Modal Popups on Click in Angular with the AmCharts XY Chart

Our goal is to display a modal window when users click on a data point. The current code we are using is as follows: constructor(public dataservice: DataserviceService, private modalService: NgbModal, private router: Router) { } ... ... bullet.events.on( ...

Guide to modifying Button on fetch response in React Native

After receiving a response from the server, I need to adjust the button based on the friends_status field in the following response: { "responseHeader": { "type": "314", "status": "200", "message": "Successfully found the profile" }, "ne ...

Retrieve JSON information from an asmx file using a C# webpage

I'm working with code that looks like this: [ScriptService] public class Titles : WebService { List<Title> Title = new List<Title>(); SqlConnection connection; SqlCommand command; SqlDataReader reader; [WebMethod()] ...

How can I retrieve the index of an element within a 2D array using JavaScript when the array is displayed on a webpage?

https://i.stack.imgur.com/GHx9p.png I am currently working on developing an Othello game board within an HTML page using Angular. The board itself is constructed from a 2D number array which I then display using the <table> tag on the webpage. Below ...

Unable to verify the authenticity of every file I choose to upload

Currently, I am in the process of learning how to develop a mean stack app, specifically focusing on creating an ecommerce type application. The main issue that I have encountered revolves around image uploading. My goal is to upload multiple files simult ...

What is the best way to loop through a formarray and assign its values to a different array in TypeScript?

Within my form, I have a FormArray with a string parameter called "Foo". In an attempt to access it, I wrote: let formArray = this.form.get("Foo") as FormArray; let formArrayValues: {Foo: string}[]; //this data will be incorporated into the TypeScript mod ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

Issue with ngModel value not being accurately represented by checkbox state in Angular 2

My issue lies with a checkbox that does not reflect its ngModel value. To provide some context, I have a Service managing a list of products and a component responsible for displaying this list and allowing users to select or deselect products. If a user d ...

A guide on enhancing Autocomplete Tag-it plugin with custom tags

Looking to expand the tags in the 'sampleTags' variable within this code snippet $(function () { var sampleTags = ['c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', &apo ...

Exploring the world of Jasmine and Angular: How to effectively mock nested methods within the Class being tested

Hello esteemed community... I have encountered a perplexing issue that appears straightforward, but has eluded my attempts at resolution... The challenge I am facing involves testing a Controller-Class in Angular. This particular codebase is laden with d ...

JSONObject does not automatically convert object attributes when calling the toString() method

I am currently working on converting an object that contains an ArrayList object as one of its attributes along with an integer. However, when I try to use toString() on the JSON object, instead of getting the actual object values, I receive pointers like ...