Looping through two arrays with *ngFor in Angular 6 is a breeze

My challenge involves working with two arrays:

firstArray= [{id: 1, name:'firstValue1'}, {id:2, name:'firstValue2'}]

secondArray= [{ "num": 1, "fullName": SecondValue1 , id:1}]

I need to display the data in the following format:

firstValue1 -------->> SecondValue1

firstValue2 -------->> 

How can I integrate these two arrays into [(ngModel)], input, or select box?

Thank you for your time and assistance!

Answer №1

To improve efficiency, consider converting secondArray from an Array to a HashMap

For instance

firstArray = [
    { id: 1, name:'firstValue1' }, 
    { id: 2, name:'firstValue2' }
];
secondArray = { 
    '1': { "num": 1, "fullName": "SecondValue1", id: 1 },
    '2': { "num": 1, "fullName": "SecondValue2", id: 2 },
}

html

<div *ngFor="let item of firstArray">
    <p>{{item.name}} --> {{secondArray[item.id]?.fullName}}</p>
</div>

Answer №2

If you're looking for a way to avoid adding an index manually to your secondArray, consider implementing this alternative:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firstArray = [
    { id: 1, name: 'firstValue1' },
    { id: 2, name: 'firstValue2' }
  ];

  secondArray = [
    { "num": 1, "fullName": 'SecondValue1', id: 1 },
    { "num": 2, "fullName": 'SecondValue2', id: 2 }
  ];

  getSecondArrayItem(id) {
    return this.secondArray.find(item => item.id === id);
  }
}

Utilize the following code snippet within the template:

<div *ngFor="let item of firstArray">
    <p>{{item.name}} --> {{ getSecondArrayItem(item.id)?.fullName }}</p>
</div>

Explore this Functional StackBlitz Demo for reference.

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

Intelligent printing of intricate arrays

Many times, floating point matrices are filled with real or imaginary numbers, and occasionally integers as well (although there is no complex integer type available). Is there a solution that doesn't involve manually formatting everything? For examp ...

Performing sequential HTTP requests on an array using Angular 4 and RxJS

Looking to perform sequential HTTP posts for each item in an array, using RxJS flatMap without success. Essentially, I'm trying to achieve the following: Each item from the 'items' array should be sent through HTTP post one by one. thi ...

The TLS connection could not be established as the client network socket disconnected prematurely

While attempting to run npm install on an Angular 5 dotnetcore project that I pulled down from source tree, everything was running smoothly on my work machine. However, when I tried to do the initial npm install on my home machine, I encountered the foll ...

Tips for presenting the cards in a professional layout

After creating a group of cards in angular using a for loop, I encountered an issue: <div class="row"> <div *ngFor="let dev_data of data" class="col-3"> <div class="card shadow"> <div class="card-body ...

Make TextField with type number forcibly show dot as decimal separator

I am currently utilizing the material-ui library to display a TextField component in my react application. Strangely, all instances of <TextField type="number /> are displaying decimal separators as commas (,) instead of dots (.), causing confusion f ...

You appear to be missing a dependency on either "@angular/core" or "rxjs" when attempting to deploy your MEAN app on Heroku. This issue must be resolved

I encountered an issue while trying to deploy my MEAN-stack application on Heroku. My app was built mainly following this tutorial series. However, during the deployment process by pushing to GIT, I received the following error: <a href="/cdn-cgi/l/emai ...

The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API. export class ListaGifsComponent { gifs : Object[] = []; urlBase = "http://api.giphy.com/v1/gifs/search?q="; termoPesquisado = "ryan+gosling"; key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn"; ...

How to configure intellisense for a webpack bundle in an ASP.NET Core project

In my development process, I utilize webpack to transpile Typescript code into Javascript and combine it into a single Javascript file. This consolidated file is then incorporated into all of my asp.net core views. While the bundled code runs smoothly, unf ...

What causes the discrepancy in errors when dealing with subtype versus regular assignments?

Below is a sample code that has been checked by TypeScript playground https://www.typescriptlang.org/play/ interface PartialCustomData { option?: number; } interface A { [key: string]: string | PartialCustomData; } interface B extends A { [k ...

Having difficulty accessing a PHP ajax post request

I've scoured every resource but can't seem to find a solution to this issue. I'm in the process of writing an ajax script, however, I am struggling to retrieve the correct value from the POST request. Here is the code I have so far: <t ...

Is there a way for me to transfer a variable to a URL?

I'm attempting to send an email that includes a link with a value obtained from Firebase. While I can successfully retrieve the value, I am unsure how to add it to the existing link. Here is my code snippet: sendinvite() { var user = firebase.a ...

Testing Angular 7 components: A guide to validating input element values

Upon updating an operational application from Angular 4 to Angular 7, I encountered a discrepancy. Consider the HTML Input below: <input id="encryptedValue" readonly class="form-control" [ngModel]="Response.encryptedText" size="50" /> Prior to the ...

What is the process of mapping an object from a JSON file to a different object?

Displayed below is my json file { "data": [ { "firstName": "Tom", "lastName": "Yoda", "type": "guest", "id": "0", "gender&quo ...

Converting changing inputs using Angular 5

I am working with a JSON translation file that contains translations for both English and German languages. Here is an example of the English translation file: en.json "COLORS": { "BLUE": "Blue", "RED": "Red", "GREEN": "Green" } ...

Change Froala toolbar symbols in real-time

I have a dropdown in my Angular application with a Froala editor below it. Depending on the selection from the dropdown, I need to update the toolbar icons of the Froala editor. Here is the relevant code: froala.component.html <select [(ngModel)]="se ...

Angular device redirection allows you to automatically redirect users based on the device

Currently in my Angular project, I am attempting to dynamically redirect users based on their device type. For example, if the user is on a Web platform, they will be redirected to www.web.com. If they are on an Android device, they should go to www.androi ...

"Embracing the Power of Font Awesome 5 in Angular 5

After using the font-awesome npm package (which is Font Awesome 4.7 version), I decided to upgrade to Font Awesome 5. In order to make this transition, I installed the following packages: "@fortawesome/angular-fontawesome": "^0.1.1", "@fortawesome/fontawe ...

Manage scss styles consistently across Angular projects with this Angular library designed to

In an effort to streamline my development process, I am looking to consolidate my commonly used styles that are defined in my Angular library. My goal is to easily leverage mixins, functions, variables, and more from my library in future projects. Previou ...

Transform a callback-based function into an Async Iterator version

Situation I have a function with an asynchronous callback structure, like so: let readFile: (path: string, callback: (line: string, eof: boolean) => void) => void However, I would much rather use a function that follows the AsyncIterable/AsyncGen ...

What significance does comparing two arrays hold in the realm of Javascript?

While working in my node.js REPL, I have created 4 arrays: a = [1,2,3], b=[], c=[4,5], d=null (although d is not actually an array). I decided to compare them directly like this: > b = [] [] > a > b true > b > a false > a > c false & ...