Discover an item in Angular by identifying an object through the given Id within the primary entity

Imagine having 2 different Objects

Item

_id
itemName
categoryId

Category

_id
categoryName
categoryDescription

With Angular, the goal is to link the categoryId in Item with the corresponding categoryName and categoryDescription, resulting in a final object structured like this.

_id
itemName
categoryId
categoryName
categoryDescription

The category fields could be nested if necessary.

EDIT: Including the relevant code snippets as requested, trimming unnecessary content.

item.ts

export interface Item {
  _id: string
  itemName: string
  categoryId: string
}

category.ts

export interface Category {
  _id: string
  categoryName: string
  categoryDescription: string
}

The service implementation.

export class CategoryService {
  private itemUrl = Url + 'items';
  private categoryUrl = Url + 'categories';

  constructor(private httpClient: HttpClient) {}

  getAllItems(): Observable<Item[]> {
    return this.httpClient.get<Item[]>(this.itemUrl);
  }

  getAllCategories(): Observable<Category[]> {
    return this.httpClient.get<Category[]>(this.categoryUr);
  }

  getOneCategory(id: string): Observable<any> {
    return this.httpClient.get(this.categoryUrl + '/find/' + id);
  }
}

The component has been updated based on @SomeStudent's response

Answer №1

Let's start by clarifying that this question is not about Angular, but rather about JS/TypeScript. Angular is a front-end framework. Here is some rough pseudo-ish code to give you a big picture overview. The key player here is the ... operator, also known as spread operator. It allows us to easily spread all properties of an object and reduce the amount of code we need to write.

If you want to dive deeper, check out these resources: freeCodeCamp, MDN Web Docs

Now, let's say you have two collections: Product and Tax:

myProducts: Product[] = [];
myTaxes: Tax[] = [];

//populate your products and tax arrays however you do

You can combine them like this:

let myProduct = this.myProducts.find(x => x._id == productId);
let myTaxForProduct = this.myTaxes.find(x => x._id == myProduct.taxId);

let { taxId, taxName, taxRate } = myTaxForProduct;
let mySpecialObject = {
...myProduct, ...{ taxId, taxName, taxRate }
}

Feel free to experiment with similar concepts in your browser's console.

  • let myProduct = {id: 1, t: 'b', n: 'c'}
  • let myTax = {id: 2, tax: 'alot', taxId: 'c'}
  • let {tax, taxId} = myTax
  • {...myProduct , ...{tax, taxId}}

The end result should be:

{id: 2, t: 'b', n: 'c', tax: 'alot', taxId: 'c'}
, which aligns with your desired outcome.

And if you're looking at the provided code snippet:

Your component.ts file

combinedItems : any[] = [];

ngOnInit() {

    combineLatest([this.taxService.getAllPdt(), 
this.taxService.getAllTax()])
.pipe()
.subscribe(([pdts, taxes] : [Product[], Tax[]) => {
   if(taxes && pdts) {
      this.products = pdts;
      this.taxs = taxes;          

      combinedItems = this.products.map(x => {
    let productProperties = {_id: x._id, productName: x.productName, taxId: x.taxId } = x;
    let taxItem = taxes.find(z => z._id == x.taxId);

    if(taxItem) {
      let taxProperties = { 
            taxName: taxItem.taxName ,
            igstRate: taxItem.igstRate, 
            cgstRate: taxItem.cgstRate, 
            sgstRate: taxItem.sgstRate 
        } = taxItem;

      let item = {...productProperties, ...taxProperties};
      return item;
    }

    return null;}
    }).filter(x => x !== null);
}

Check out this JS Fiddle example.

Answer №2

take a look at this demonstration:

const Products:any[]=[];
Products.push({_id:1,productName:'item1',taxId:101})
Products.push({_id:2,productName:'item2',taxId:102})

const Taxes:any[]=[];
Taxes.push({_id:1,taxName:'taxName1',taxRate:201})
Taxes.push({_id:2,taxName:'taxName2',taxRate:202})


const findTaxID=102; //desired taxId

const ProductResult=Products.find(x => x.taxId == findTaxID);
const TaxResult=Taxes.find(x => x._id == ProductResult['_id']);

const finalOutcome={_id:ProductResult['_id'],productName:ProductResult['productName'],taxId:ProductResult['taxId'],
taxName:TaxResult['taxName'],taxRate:TaxResult['taxRate']}

console.log(finalOutcome)

and here is the outcome:

https://i.sstatic.net/kAmA1.png

I trust this aids you!

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

Setting up a variable with no operation assigned to it

As I delved into the Angular utils source code, I stumbled upon this interesting line: export const NOOP: any = () => {}; It seems pretty straightforward - a variable that doesn't perform any operation. But then, within the same library, there is ...

Choose the default radio button with Angular Material

Utilizing Angular Material, I am working with a mat-radio-group and a mat-radio-button. Despite my efforts to select a default radio button object option, it is not getting selected automatically. Below is the code snippet: app.component.ts import { Comp ...

AngularJS attempted to open $modal, but it encountered an error because the controller named <controllername> was not registered

Currently, I am in the process of enhancing a web application that was originally developed using AngularJS with typescript instead of JS. I have a controller set up with a specific template that I want to display in a modal using $modal.open. However, I ...

Obtaining a Bearer token in Angular 2 using a Web

I am currently working on asp.net web api and I am looking for a way to authenticate users using a bearer token. On my login page, I submit the user information and then call my communication service function: submitLogin():void{ this.user = this.l ...

The automatic type inference in Typescript is faulty

I am currently working with TypeScript version ^4.1.3 and have developed a REST API that deals with albums and art collections. Before sending the response to the web client, I make sure to remove the userId property from the collections. Below are my Alb ...

managing simultaneous opening of multiple dropdown buttons in Angular

Currently, I am actively involved with Angular development, I have constructed a tree-like framework As you navigate down the tree structure, there is a dropdown button labeled "Dropdown" The main issue arises when clicking on the "Dropdown" button, as m ...

Combining and Filtering Arrays of Objects with Angular

I possess: arrayBefore arrayBefore = [{name:'n1', items: [i1]}, {name:'n2', items: [i2]}, {name:'n1', items: [i3]}] I desire to craft a function: myFunction myFunction(arrayBefore) In order for it to generate: arrayAfte ...

What could be causing the failure of authorization for the MVC and Angular application?

My application consists of an MVC framework integrated with an Angular app. The MVC side handles server-side operations, authenticates users, and saves cookies. However, when I transition to the Angular app, I receive a "not authorized" message while att ...

How can one point to a parameter within the documentation of a TypeScript function?

I am attempting to incorporate parameter references in function descriptions like this: /** * Deletes the Travel Cost with the given {@param id} * @param id the id of the travel cost to be deleted */ deleteTravelCost(id: number): Observable<{}> { ...

Launching superheroes application developed with Angular 2

I followed the heroes tutorial and customized my own Angular2 application using some components. Although it resembles the heroes tutorial, I have successfully set up everything with my IDE and npm. Now, I am facing challenges in deploying my application i ...

Anticipated request for spy navigation with path '/members' was expected, but unfortunately was not triggered

I am facing an issue with a service method that performs an HTTP delete operation. The expected behavior is that upon successful deletion, the page should be redirected to another location. However, during testing, I noticed that the router navigation func ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

The function navigator.canShare() encountered a permissions denial while running in Typescript

Currently, I am in the process of developing an Angular8 PWA and have successfully implemented webshare to share text content. To my excitement, Chrome has now extended its support for file sharing starting from May 2019. However, while attempting to int ...

Unexpected error: Angular 4 TypeScript validation issue - An object literal can only define recognized properties

excellent customer service import {Account} from '../models/Account'; export class AccountingService { domain: string = "http://localhost:3000/api"; constructor(private http: HttpClient) { } getAccounts(){ return this.http.get&l ...

Build modern web applications with Visual Studio 2015/2017 using React and TypeScript for dynamic

Has anyone successfully found a comprehensive react+typescript tutorial for a Visual Studio 2015/2017 MVC project that actually works, from beginning to end? I attempted to install the NuGet packages "Reactjs Mvc4" and "typescript", created a .tsx file, a ...

Filling the text and value array using a collection of objects

Need help with populating an array of text and value using an array of objects in Angular. Below is the JSON data containing the array of objects. Declaration public AuditYearEnd: Array<{ text: string, value: number }>; Assignment - How can I assi ...

Navigating with Angular Routing Data

I'm facing a minor issue. I need to transfer data from my products section to the corresponding single product page. The setup involves a products page showcasing 10-15 products with titles, brief descriptions, images, and a button for more informatio ...

The tslint exclusion is not functioning properly for tsoa endpoints

I'm trying to remove the routes.ts file generated by tsoa routes from being compiled by tslint. I've used the exclude option but it doesn't seem to be working specifically for routes.ts. The exclude option works for other files, except for r ...

TS2345: The argument provided, which is of type 'Event', cannot be assigned to the parameter expected, which is of type 'HtmlInputEvent'

I am facing an issue while trying to upload a file, and I could use some assistance in resolving it. Angular-----Error: src/app/admin/producto/create-producto-dialog.html:38:47 - error TS2345: Argument of type 'Event' is not assignable to parame ...

Tips on incorporating TypeScript into jQuery's live event syntax

Encountered an Issue: $(document).on('click', '#focal-toggle', function(this: HTMLElement | HTMLElement[], e:MouseEvent) { Triggered Error Message: { "resource": "/root/dev/work/OutrunInteractive2020/webfocusview/plain/ts/webfocu ...