Search for a matching number asynchronously in an object that contains a set of numbers

I am looking to retrieve objects asynchronously based on their category. In other words, I want my products to be loaded asynchronously by category.

Currently, I have a function named 'getProductByID' that searches for a product using its ID.

  getProductByID(id: number): Observable<ProductModel> {
    return of(ProductsList.find((product) => product.id === id));
  } //this function works properly

//I attempted to create a similar function for categories,
//but I'm unsure how to match the category from the array

  getProductsByCategory2(selectedCategory: CategoryModel): Observable<ProductModel[]> {
     return of(ProductsList.find((product) => product.category === selectedCategory)
   } //this approach is not successful

  getProductsByCategory(selectedCategory: CategoryModel): ProductModel[] {
    const products: ProductModel[] = [];
    for (const product of ProductsList) {
      for (const category of product.category) {
        if (category === selectedCategory.id) {
          products.push(product);
        }
      }
    }
    return products;
  }// this function also works as expected, but does not provide asynchronous results

I need to identify all products that match with a specific category ID. Keep in mind that each product can have multiple categories assigned to it.

Answer №1

To retrieve the initial matching element, utilize the find function or experiment with the filter function.

Remember: In your getProductsByCategory2 function, ensure you are comparing product.category to selectedCategory efficiently. JavaScript utilizes object comparison by reference, so opt to use primitive values for a more effective comparison.

Answer №2

To enhance data retrieval, employ the filter method from rxjs/operators within your service or any other suitable location.

return of(ProductsList.pipe(
    map(result => result.filter(item => item.userId == 1)) // Customize filtering here
))

Subsequently, subscribe to the refined dataset for further processing and utilization.

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

Ensure the security of a generic type's value by enforcing type safety

Is there a way to utilize generics to ensure that the type of a value is specific? // Sample array const testArr = [ { id: 3, name: 'Spaghetto', // Type 'string' here shouldNotWork: 3.14, // Type 'number' here ...

Connecting the outcome of a Promise with an Observable

Forgive me if this is a silly question. I searched high and low but couldn't find the answer I need. I'm trying to figure out how to pass the value for index, which is returned in the Promise, as an argument to my Observable: deleteFavorite(tok ...

What steps can I take to adapt my component in order to incorporate RxJs?

I am trying to gain proficiency in RxJs and, for educational purposes, I am interested in understanding how to modify the following code or if it is even feasible. Within my project, there is a component called MeetingObjectComponent which contains a chil ...

I'm seeking a way to access the input element within the InputGroup component of BlueprintJs in my

The BluePrintJS React InputGroup component offers a convenient user interface for modern applications. However, it does not provide direct access to the internal <input> element. There are two primary reasons why I need to access the input element: ...

Facing issues with Observable and HTTP JSON in Angular

I've been struggling with an issue where I'm unable to display the "datos" variable in the *ngFor loop. I suspect the problem lies in the rendering process, so I tried implementing "Observable", but unfortunately, it didn't resolve the issue ...

Poorly packaged library - Custom Angular library - Node Package Manager

Recently, I've been delving into the process of publishing a simple Angular library on NPM. Despite following various tutorials (like those found here, here, and here), I faced difficulties when attempting to use it in a test project. MY JOURNEY In s ...

How to Publish an Angular 8 Application on Github Pages using ngh

Currently in my angular 8 project, I am encountering the following issue while running the command: ole@mkt:~/test$ ngh index.html could not be copied to 404.html. This does not look like an angular-cli project?! (Hint: are you sure that you h ...

Unexpected Error with Angular Abstract Class Definition

I've encountered a peculiar Type Error while working with Abstract Classes in Angular 16. Error: Uncaught (in promise): TypeError: this.httpService.get is not a function Could it be that my interpretation of using Abstract Classes is off? Everythin ...

Testing a reusable component in Angular using unit testing techniques

Currently, I am creating a test for an AppleComponent which has the following type: <T,U extends BananaComponent<T>>. This component also contains BananaComponent<T>. Target Component export class AppleComponent<T,U extends BananaCom ...

The issue of PrimeReact AccordionTab failing to render when enclosed within a custom component

I'm encountering an issue with my specialized FilterAccordionTab component, which is an extension of PrimeReact's (V8) AccordionTab. It appears that the content is not being displayed when using this custom component. However, everything function ...

Angular: Refresh mat-table with updated data array after applying filter

I have implemented a filter function in my Angular project to display only specific data in a mat-table based on the filter criteria. Within my mat-table, I am providing an array of objects to populate the table. The filtering function I have created loo ...

Assigning enum type variable using string in TypeScript

How can I dynamically assign a value to a TypeScript enum variable? Given: enum options { 'one' = 'one', 'two' = 'two', 'three' = 'three'} let selected = options.one I want to set the variable " ...

Include type declarations for property values that resemble arrays in a generic object

Imagine you have a function that: receives an object with multiple properties and a property name; checks if the property holds an array; if it does, performs an action (such as printing the values it contains) Here's an illustration: function pro ...

Special Syntax for Defining Custom Record Keys in TypeScript

In the process of creating a small library, I am focused on enhancing type safety for the following object: export const ErrorCodeMap: Record<string, [string, number]> = { NOT_FOUND: ['1001', 222], ALREADY_EXISTS: ['1002', 111 ...

Discovering the index of an item in Angular

My delete function emits socket.io to update the other party's items list and remove the specific item. The issue arises when I receive the socket data as I struggle to find the matching item to update it. Logic User 1 deletes a message User 2 receiv ...

Creating a dynamic row in an HTML table with elements inside

I have an array of numbers in my angular application that I need to display in an HTML table without truncating them and ending with a comma. Each row should display a maximum of 20 values. How can this be achieved? The array looks like this - let arr ...

The list fails to update after an item has been removed

I'm facing an issue with refreshing my lists in the view after deleting an item. The deletion process works correctly as the item is removed when I manually refresh the page. Here's a look at my component class: import { Component, OnInit, Pipe} ...

Developing dynamic-sized tuples in TypeScript

Recently, I was attempting to develop a zipper for arrays. For instance, if the user inputs 3 arrays with sizes of 3, 5, and 12, the output array of tuples would be the size of the largest array. The output consists of tuples containing elements at a speci ...

Is there a way to implement Rust's enum variant classes or Kotlin sealed classes in TypeScript?

When working with HTTP responses in TypeScript, I am interested in creating a variant type that can represent different states. In Rust, a similar type can be defined as: enum Response<T> { Empty, Loading, Failure(String), Success(dat ...

Guide to implementing a specified directive value across various tags in Angular Material

As I delve into learning Angular and Material, I have come across a challenge in my project. I noticed that I need to create forms with a consistent appearance. Take for example the registration form's template snippet below: <mat-card> <h2 ...