What is the best way to extract specific elements from a nested object array using TypeScript?

I am able to filter the bookings based on b.building.id here:

bookings.filter(b => b.building.id == this.filter.buildingId);

However, I am struggling to filter the bookings object array if the b.modules is also an array. Here is my unsuccessful attempt:

bookings.filter(b => b.modules.programme.facultyId == this.filter.facultyId);

And another unsuccessful attempt:

bookings.filter(b => {
  for (let module of b.modules) {
    module.programme.facultyId == this.filter.facultyId;
  }
});

Update:

Below is an example of a JSON result for bookings:

[
  {
    "id": 2,
    "semesterId": 1,
    "room": {
        "capacity": 17,
        "code": null,
        "building": {
            "id": 5,
            "name": "Faculty of Science"
        },
        "id": 15,
        "name": "FSB 1.10"
    },
    "building": {
        "id": 5,
        "name": "Faculty of Science"
    },
    "bookDate": "2020-11-10T00:00:00",
    "timeSlots": [
        {
            "id": 1,
            "startTime": "1900-01-01T07:50:00",
            "endTime": "1900-01-01T08:40:00"
        },
        {
            "id": 2,
            "startTime": "1900-01-01T08:50:00",
            "endTime": "1900-01-01T09:40:00"
        }
    ],
    "modules": [
        {
            "id": 5,
            "name": "Computer Systems and Information Technology",
            "code": "SS-1202",
            "lecturers": [
                {
                    "id": 4,
                    "name": "Lim",
                    "title": "Dr."
                }
             ],
            "programme": {
                "id": 1,
                "name": "Computer Science",
                "shortName": null,
                "facultyId": 1
            }
        }
    ]
  }
]

Answer №1

When searching through bookings, you can narrow down results by filtering through modules based on facultyId matching the filter's facultyId.

If facultyId within module.programme is unique, you have the option to use the find method instead:

bookings.filter(b => b.modules.find(module => module.programme.facultyId == this.filter.facultyId));

Answer №2

Here's a different approach

There may be two key elements that are overlooked. First, the filter function is not properly returning a value after the filter operation. Additionally, there could be instances where the this reference is missing.

const self = this;

bookings.filter(b => {
  return b.modules.filter(module.programme.facultyId == that.filter.facultyId)
});

Answer №3

Let's break down the code:

const filteredResults = bookings.filter(booking => booking.modules.filter(module => module.programme.facultyId === booking.facultyId));

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

react state change not triggering re-render of paragraph

I recently started learning react and web development. To streamline my work, I've been using ChatGPT, but I'm facing an issue that I can't seem to solve. I'm trying to fetch movie descriptions from the TMDB API using movie IDs, but des ...

Encountering issues with Typescript when using absolute paths

After updating a forked repository, I noticed that TypeScript is no longer recognizing absolute paths. Surprisingly, I have not made any changes to my tsconfig.json: { "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, ...

"Guidance on setting up my input text box in Angular to allow for selection of required fields

I'm currently in the process of developing a form where all fields are required. My goal is to have the Next button move on to the subsequent form only if all required fields have been filled out. However, I seem to be encountering an issue where desp ...

Update the URL in an Angular application once the app has finished loading

I have a client who is using an existing angular application without the access to its source code. We are currently in the process of rebuilding the app, but there is an immediate need to edit the content of a specific page. To achieve this, I have extra ...

Display a button within a table depending on the content of adjacent cells

Below is the code snippet I'm currently working with: <tbody *ngIf="packages"> <tr *ngFor="let package of packages"> <td class='checkbox'> <label class="css-control css-co ...

A practical guide to troubleshooting typescript errors when exporting a map component

I encountered a typescript error when trying to export the map component with GoogleApiWrapper. It works fine when not wrapped in GoogleApiWrapper, but all my attempts to resolve the issue have failed. I would appreciate it if someone could review the code ...

Angular 7 encountering issues retrieving HTTP headers

Is it possible to perform web scraping without using Python? I am attempting to make a simple HTTP GET request from a web Angular app, but I am running into an issue with the response. Specifically, I need to access the headers in order to obtain the csrft ...

The TSX file is encountering difficulty rendering an imported React Component

Upon attempting to import the Day component into the Week component (both .tsx files), an error is thrown: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

Why is the ngx slick carousel not functioning properly within the ngx-bootstrap accordion in Angular 7?

I am trying to incorporate the ngx-slick-carousel inside an ngx-bootstrap accordion and tabs. The tabs are located within the accordion, but when I try to add the carousel outside of the accordion, it works fine. How can I successfully add it inside the ...

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

Exploring the application of keyof with object structures instead of defined types

Looking to create a new type based on the keys of another object in TypeScript. Successfully achieved this through type inference. However, using an explicit type Record<string, something> results in keyof returning string instead of a union of the ...

In Typescript, a function that is declared with a type other than 'void' or 'any' is required to have a return value

I'm a beginner in Angular2/Typescript and I am encountering an error while trying to compile my project: An error is showing: A function that has a declared type other than 'void' or 'any' must return a value. Here is the code sn ...

Error encountered: NgModel provider missing! Issue arises when attempting to incorporate ngControl with TypeHead in Bootstrap 4 in an Angular 2 project

I am currently working on implementing form validation using ngControl on a Bootstrap 4 typeahead control in AngularJS 2. See the code snippet below: <input [(ngModel)]="model.brand" [typeahead]="model.brands" ng-model-options="{'updateOn': & ...

JavaScript: Collecting data into an array of objects

Is there a more efficient way to fetch a specific object from an array of objects without using a for loop? Here is an example of the array of objects: 0: {code: "YJYDWO1", route_id: 1} 1: {code: "YJYDWO2", route_id: 2} 2: {code: "YJYDWO3", route_id: 3} 3 ...

Having difficulty transferring types to and from a custom module?

I'm currently faced with an issue while working on a typescript module within a larger monorepo. I am having difficulty importing types from one package into another via node modules. The types are located at ./types, and my package.json contains a ke ...

Utilizing service-based global objects in Angular applications

Upon entry into my application, the GlobalApplicationController initializes several services that are utilized throughout the entire application, such as subscribing to sockets. It would be quite beneficial to have a CurrentUser object available - however, ...

Angular2 displays an error stating that the function start.endsWith is not recognized as a valid function

After switching my base URL from / to window.document.location, I encountered the following error message: TypeError: start.endsWith is not a function Has anyone else experienced this issue with [email protected]? ...

Steps to disable TypeScript error messages for unused variables

I encountered an issue in my Angular CLI that says: jest.config.js is part of the TypeScript compilation but it's unused. Add only entry points to the 'files' or 'include' properties in your tsconfig. Additionally, I have a few o ...

The variable type 'editor.IStandaloneCodeEditor' does not match the parameter type 'monaco.editor.IStandaloneCodeEditor'

After installing the "monaco-editor" package using the command npm i monaco-editor, I encountered a type error in my source code. Can someone help me understand why this error is happening and how I can resolve it? This is the package file content: { "p ...

Angular Validation for Start and End Dates

<tr> <td class="p-10"> <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Tarih" name="date" id="date" #date="ngModel" ngModel required> <mat-datepicker-toggle matSuffix [for]="p ...