Linking arrays through a foreign identifier in Angular TypeScript

I have a collection of JSON objects stored in the InMemoryDataService (mock server) and services.ts file. These objects contain various elements that I want to display on an HTML page by replacing productId and shopId with product.name and shop.name respectively, based on their unique IDs. How can I achieve this?

 createDb() {
const prices = [
  { id: 11, price: 3.40, dateFrom:'12/3/19', dateTo: '15/3/19', productId: 3,shopId: 4},
  { id: 12, price: 5.40, dateFrom:'6/3/19', dateTo:'22/3/19', productId: 1,shopId: 4}, 
  { id: 13, price: 8.00, dateFrom:'21/3/19', dateTo:'23/4/19', productId: 2,shopId: 2},
  { id: 14, price: 6.30, dateFrom:'17/3/19', dateTo:'23/3/19', productId: 3,shopId: 3},
];

const products = [
  {id:1, name: 'Barilia', description: 'Good Coffee', category :'Espresso', tags:['Coffe','Espresso'], withdrawn: false},
  {id:2, name: 'Nespresso', description: 'Good Coffee', category :'Espresso', tags:['Coffe','Espresso'], withdrawn: false},
  {id:3, name: 'Island', description: 'Good Coffee', category :'Cappuchino', tags:['Coffe','Cappuchino'], withdrawn: false},
  {id:4, name: 'Lavanca', description: 'Good Coffee', category :'Espresso', tags:['Coffe','Espresso'], withdrawn: false}
];

 const shops = [ 
  { id: 1, name: 'Coffee Island',address: 'Agioi Theodwroi 10,Petroupoli,14432', Ing: 30.5 , Iat: 54.44,tags ['Coffee','Espresso'],withdrawn:false},
  { id: 2, name: 'Coffee Bear',address: 'Valsamou 42,Kifisia,14675', Ing: 32.5 , Iat: 60.43,tags:['Coffee','Espresso'], withdrawn:false },
  { id: 3, name: 'Coffee Lab',address: 'Thiseas 10,Marousi,31313', Ing: 29.5 , Iat: 50.44, tags:['Coffee','Espresso'], withdrawn:false },
  { id: 4, name: 'Starbucks',address: 'Kifisias 7,Kifisia,12345', Ing: 27.8 , Iat: 37.9,tags:['Coffee','Espresso'], withdrawn:false  }
];

return {products,prices,shops};

Answer №1

To enhance your prices JSON, iterate through and include the name property as shown below:

Include product name & shop name

prices.forEach(x=>{
    x['productName']= products.find(y=>y.id === x.productId).name;
    x['shopName']= shops.find(y=>y.id === x.shopId).name;
});

Answer №2

Utilize the id to browse your collection of items.

const selectedProduct = products.find(item => item.id === productId)

Answer №3

When loading them asynchronously, you can utilize a getter to access the data like so

    private prices = [
        { id: 11, price: 3.40, dateFrom: '12/3/19', dateTo: '15/3/19', productId: 3, shopId: 4 },
        { id: 12, price: 5.40, dateFrom: '6/3/19', dateTo: '22/3/19', productId: 1, shopId: 4 },
        { id: 13, price: 8.00, dateFrom: '21/3/19', dateTo: '23/4/19', productId: 2, shopId: 2 },
        { id: 14, price: 6.30, dateFrom: '17/3/19', dateTo: '23/3/19', productId: 3, shopId: 3 },
    ];

    private products = [
        { id: 1, name: 'Barilia', description: 'Good Coffee', category: 'Espresso', tags: ['Coffe', 'Espresso'], withdrawn: false },
        { id: 2, name: 'Nespresso', description: 'Good Coffee', category: 'Espresso', tags: ['Coffe', 'Espresso'], withdrawn: false },
        { id: 3, name: 'Island', description: 'Good Coffee', category: 'Cappuchino', tags: ['Coffe', 'Cappuchino'], withdrawn: false },
        { id: 4, name: 'Lavanca', description: 'Good Coffee', category: 'Espresso', tags: ['Coffe', 'Espresso'], withdrawn: false }
    ];

    private shops = [
        { id: 1, name: 'Coffee Island', address: 'Agioi Theodwroi 10,Petroupoli,14432', Ing: 30.5, Iat: 54.44, tags: ['Coffee', 'Espresso'], withdrawn: false },
        { id: 2, name: 'Coffee Bear', address: 'Valsamou 42,Kifisia,14675', Ing: 32.5, Iat: 60.43, tags: ['Coffee', 'Espresso'], withdrawn: false },
        { id: 3, name: 'Coffee Lab', address: 'Thiseas 10,Marousi,31313', Ing: 29.5, Iat: 50.44, tags: ['Coffee', 'Espresso'], withdrawn: false },
        { id: 4, name: 'Starbucks', address: 'Kifisias 7,Kifisia,12345', Ing: 27.8, Iat: 37.9, tags: ['Coffee', 'Espresso'], withdrawn: false }
    ];

    get data() {
        return this.prices.reduce((sum, item) => {
            return [...sum, {
                ...item,
                shop: this.shops.find((shop) => shop.id === item.shopId),
                product: this.products.find((product) => product.id === item.productId),
            }];
        }, <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

Having trouble installing npm packages due to an error

As I attempt to install my npm packages, a frustrating error occurs. What steps should I take to resolve this issue? npm ERR! code EINVALIDTYPE npm ERR! typeerror Error: Argument #5: Expected object but got string npm ERR! typeerror at inflatableChild ...

How can I handle a queue in Angular and rxjs by removing elements efficiently?

I'm facing a challenging issue with my code that I need help explaining. The problem lies in the fact that a function is frequently called, which returns an observable, but this function takes some time to complete. The function send() is what gets c ...

Using ngIf with Promises causes a malfunction

I have extensively tested this issue and I am unable to understand why the code below is not functioning as expected. The problem arises when the @Input variable is received and the user object is fetched from the service, the ngIf directive in the templat ...

Encountering issues with Semver while working on building an Angular 4 IMAP client

I am currently working on integrating an Imap Client into my Angular 4 app. I came across a helpful node module for implementing Imap using npm: Repository However, I encountered an issue. After adding the following line in angular-cli.json: "scripts": ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

Enhance TypeScript class declarations with additional properties

Our company has developed its own test framework for our software because we found it difficult to use an open-source framework within the context of our specific development needs. Recently, I took on the task of creating Typescript Definition Files to e ...

Setting a value to a FormBuilder object in Angular 2 with Typescript

During my use of Reactive form Validation (Model driven validation), I encountered an issue with setting the value to the form object on a Dropdown change. Here is my Formgroup: studentModel: StudentModel; AMform: FormGroup; Name = new FormControl("", Va ...

Distributing elements evenly across the parent width using Angular FlexLayout for a responsive design

I need to create 3 div squares: div-left, div-middle, and div-right, each with a width of 300px. These squares should be arranged horizontally within the parent div main-section, which will adjust its size based on the screen width, being 1300px if the scr ...

Guide on integrating dependent components into an independent component within Angular 14 and above

Can someone explain the process of importing a non-standalone component into a standalone component, specifically when the non-standalone component is declared in an ngModule? ...

Execute service operations simultaneously and set the results in the sequence they are received

I am faced with a challenge involving multiple service methods that fetch data from various servers. The responses from these APIs come in at different times, and I need to store the responses in variables as soon as they are received. Here are my service ...

Tips for Incorporating Material Design Lite into Angular2

I have encountered a minor issue while trying to incorporate material design into Angular2. I am using the latest version of Angular2, but the MDL framework seems to be incompatible. Here is what I have done so far: npm install material-design-lite --sav ...

Guide on displaying and handling server-side validation errors within an angular form

I recently started working with Angular and encountered a problem I can't seem to solve. In my form, I need to display server validation errors from a Laravel REST API response. Although I can see the error message in the console, I'm unsure how ...

The TypeScript compilation is not able to find index.ts at the moment

When I tried to run 'ng serve', I encountered the following error message: The TypeScript compilation is missing node_modules/angular2-indexeddb/index.ts. It is crucial to ensure that this file is included in your tsconfig under the 'file ...

Adding styles to specific child nodes within a p-tree component in PrimeNG

Starting off with a demonstration example: Check out this StackBlitz for primeng p-tree. I am utilizing primeng to construct a structure for polls and answers using p-tree. The hierarchy is as follows: Participants --> Polls --> Questions --& ...

Creating a promise instance with the axios create method

As someone who is new to TypeScript, I am learning as I go along. One thing I want to do is create an axios instance that can be reused in my code by passing props only where needed. The framework I'm using is React. // Located in a utils folder // a ...

Getting node siblings within an Angular Material nested tree: A comprehensive guide

Struggling to retrieve the list of sibling nodes for a specific Angular Material tree node within a nested tree structure. After exploring the Angular Material official documentation, particularly experimenting with the "Tree with nested nodes," I found t ...

Launch Outlook Email with Attachment through Angular on a click event

I am developing a client side application that utilizes Angular 7 for the frontend and C# for the backend. Here is the requirement: When a button on the UI, labeled as "open Mail with Attachment", is clicked, I need to be able to open an email in Outlook ...

The PrimeNG confirmation dialog (Overlay) does not come with any default styling (CSS)

I implemented a PrimeNG confirmation dialog based on the example from their official documentation: component.html <p-confirmDialog appendTo="body" #cd> <p-footer> <button type="button" pButton class="btn btn-primary btn-norma ...

Angular2-starter configuration setup with environment-based variables (such as .env or .conf) for testing and production settings

Frameworks like PHP Laravel often include files for local configuration, separate from dev, test, and production environments. How can a configuration file be provided for an angular-starter project that contains all local environment variable values (su ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...