typescript What is the best approach to searching within a nested array?

I am struggling to extract a specific value from a nested array within an array.

Here is an example structure of my array:

[
    {
        ConcessionId: 1,
        ConcessionName: "Coyotes",
        KnownAs: [
          {
            TeamId: 1,
            Name: "Arizona Coyotes",
          },
          {
            TeamId: 2,
            Name: "Phoenix Coyotes",
          }
        ]
    },
    {
        ConcessionId: 2,
        ConcessionName: "Devils",
        KnownAs: [
          {
            TeamId: 3,
            Name: "Colorado Rockies",
          },
          {
            TeamId: 4,
            Name: "New-Jersey Devils",
          }
        ]
    }
]

I need help with writing a function that will return the team name based on a provided parameter. For instance, if the parameter value is 3, I expect the function to return "Colorado Rockies":

public getInfo(_TeamID) { 
    const concession: ConcessionInfo[] =  this.concessionList$.filter(function (x) {
      x.KnownAs.filter( (y)=> {
          y.TeamId= +_TeamID;
          return y.Name;
      })
    })

}

I have tried using filters in various ways but couldn't achieve the desired result. It seems like there should be a more efficient way than using nested loops.

Any suggestions would be greatly appreciated. Thank you!

Answer №1

Instead of utilizing the filter method (which essentially functions similarly to a for loop), you could opt to use forEach on both arrays. Given your current data structure, there seems to be no alternative way around it.

getInfo = (_TeamID) => {
  let teamName = '';
  this.concessionList$.forEach(entry => {
    entry.KnownAs.forEach(team => {
      if(team.TeamId === _TeamID){
        teamName = team.Name;
        return; // terminate the loop.
      }
    })
  });
  return teamName;
}

Here is an example that shows the solution in action:

https://stackblitz.com/edit/double-for-lopp

EDIT Upon examining the polyfill implementation of filter from Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter, which mimics the native implementation of filter, it's evident that it loops through the entire array much like a forEach loop. The distinction lies in the fact that the filter method generates a new array based on the boolean condition within the callback function, while a forEach loop does not yield any output.

Answer №2

If you have an array called myArray that contains the provided data, the code snippet below will be compatible with Typescript versions 3.7 and above.

public retrieveInfo(teamId: number): string | undefined {
    const team = this.concessionList$
      .map(concession => concession.KnownAs)
      .reduce((a, b) => a.concat(b), [])
      .find(team => team.TeamId === teamId)
    return team ? team.Name : undefined
}

How to use:

this.retrieveInfo(3) // Output: Colorado Rockies

But how does this actually work?

To understand this, let's consider what find does. For example:

const result = [{name: 'foo', age: 1}, {name: 'bar', age: 2}]
    .find(people => people.name === 'foo')

console.log(result) // Output: {name: 'foo', age: 1}

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

Dependency management with various versions of an NPM package

I'm feeling a bit puzzled about NPM package versions. In my ionic2 app's packages.json file, I have a dependency on [email protected]. Additionally, I have the latest version of ionic-native which is dependent on [email protected]. Th ...

Typescript: Subscribed information mysteriously disappeared

[ Voting to avoid putting everything inside ngOnit because I need to reuse the API response and model array in multiple functions. Need a way to reuse without cluttering up ngOnInit. I could simply call subscribe repeatedly in each function to solve the p ...

Is it possible to retrieve data from numerous tables and consolidate it all into a single array?

Hello everyone, I'm trying to figure out the most efficient way to achieve the following task: I need to query up to 5 tables (depending on user input), retrieve the results, and combine them into one single array. For example, if I query table A and ...

Typescript struggles to identify properties that have no business being there

In my function for formatting data, the "values" contained within this data are clearly defined. However, TypeScript is failing to recognize new properties that are invalid when mapping these values. The issue can be best understood by looking at the code ...

What are some ways to retrieve a summary of an Angular FormArray containing controls?

In my FormGroup, I have a FormArray called products which contains dynamic controls that can be added or removed: FormGroup { controls { products (FormArray) { 0 : {summary.value: 5}... 1 : {summary.value: 8}.. there can be N of these co ...

Creating a Typescript HttpInterceptor and ensuring its compatibility with minification techniques

Currently, I am trying to implement an Angular HttpInterceptor based on the solution provided in this Stack Overflow response: However, I am struggling with the factory method: public static Factory($q: ng.IQService) { return new AuthenticationInter ...

Having trouble changing the query string in the URL with Angular 4?

My search form includes various filters such as text inputs, checkboxes, and radio buttons. Whenever the user interacts with these filters, the query string in the URL needs to be updated. Consider the following scenario: http://example.com/search?myFilt ...

In TypeScript/Angular, what is the best way to share model variables between a Service class and a controller class?

Is there a way for the Controller and Service classes to access the same model without explicitly passing it? For example: Controller Class : import { SearchModel } from "../../models/SearchModel"; import { SearchService } from "../../components/SearchS ...

The "ng2-CKEditor" package is experiencing compatibility issues with TypeScript in Angular 2

Currently, I am in the process of setting up CKEditor in my angular2 application. My backend platform is node.js and for this purpose, I am utilizing the ng2-CKEditor npm module. Below, you can find snippets from respective files. index.html:: <html& ...

Steps to Turn Off Angular 2 Material Input Field

Please carefully review the Description below before proceeding: This is an HTML file containing code snippets: <div class="row col-md-2"> <mat-form-field appearance="outline" class="nameInput col-md-2"> <mat-label>One< ...

Tips for iterating over an array that implements either of two interfaces in TypeScript

The objective is to develop a reusable method for filtering out items from an array that implements one of two interfaces Providing a code example would be most helpful: interface IDuration { start: number; end: number; } interface IRelativeDuration ...

Bringing in the typescript 4 package to use in typescript version 3.8.3

I've been working on a project that is utilizing typescript 3.8.3, and I'm currently attempting to import a newer package (specifically win32-api). I initially didn't anticipate any issues since the package is compiled to JavaScript. At wor ...

Could a tslint rule be implemented in Typescript classes to ensure method return types are enforced?

After diving into the tslint rules here, it seems that although the typedef rule's call-signature option might be close to what I need, it doesn't address the absence of a return type. Is there a specific rule (if one exists) that can enforce re ...

Obtaining attribute data value upon selection change in Angular 4

Having trouble retrieving the value from data-somedata in my code... <select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (change)="menuChange($event)"> <option *ngFor="let menu_optional of menu_optionals" value= ...

Angular : Is toFixed() functioning properly with one value but not with the other one?

My form has 2 inputs, each calling the calculeSalaire() function. calculeSalaire() { this.fraisGestion = this.getFraisGestion(); this.tauxFraisGestion = this.getTauxFraisGestion(); this.salaireBrut = this.getSalaireBrut(); this.salaireNet = this.g ...

What is the process for creating a class in TypeScript?

Here is an example of the object structure I am working with: { "info" : { "title" : '123}, "details": [ {"desc": "d1"}, {"desc": "d2}] } I am currently in the process of defining ...

Can the data cells of columns be dynamically adjusted to align them on a single vertical line?

For some time now, I have been grappling with a CSS issue. I am working with a table that has 3 columns displaying departures, times, and situational text for scenarios like delays or cancellations. However, as evident from the images, the alignment of th ...

A different approach to handling multiple constructors in Angular 4

Angular 4 does not support having multiple constructors, so I need to find a cleaner way to instantiate my object. This is what my model looks like: export class SrcFilter { constructor(public firstList?: Array<String>, public secondList?: Arra ...

Scrolling through a list in Angular using cdk-virtual-scroll-viewport while selecting items via keyboard input

Looking to implement a customized Autocomplete feature. As the user begins typing, a small window should appear with selectable options. I want users to have the ability to navigate and select an option using their keyboard. For instance: - User types "H ...

Create a tuple type that encompasses all possible paths within a recursive object configuration

Consider the following templates for 'business' types, representing compound and atomic states: interface CompoundState<TName extends string, TChildren extends { [key: string]: AnyCompoundState | AnyAtomicState }> { type: 'parent&ap ...