What is the best way to retrieve a nested object array using a Signal in Angular/Typescript?

In my Angular/Typescript code, I am encountering an issue with filtering a nested object array based on the object property where value === 'event'.

Despite my efforts, the code is returning the parent object array CalendarModel[] instead of the expected nested object array.

By adding :{types} to the variables/filters, I can see the types that Angular recognizes.

getAllEvents: Signal<CalendarModel[]> = computed(() => this.dataService.allInformation()?.allCalendarInformation?.filter(calendar: CalendarModel => calendar?.events?.filter(event: CalendarEvent=> event.type === 'event').filter(event: CalendarEvent => {
    return new Date(event.date).getTime() >= new Date().setHours(0, 0, 0, 0);
  }))
);

Here is the model structure:

allCalendarInformation: CalendarModel[];
export interface CalendarModel {
  date: Date;
  events: CalendarEvent[];
}
export interface CalendarEvent {
  imageUrl?: string
  title: string;
  date?: Date;
  location?: string;
  time?: string;
  description: string;
  type?: string;
  featured?: boolean;
}

Am I missing something in my code logic?

Despite drilling down into events and attempting to retrieve events with type === 'event', Typescript is indicating that the overall object from getAllEvents is of type CalendarModel[] instead of CalendarEvent[]. Why is this happening?

I have successfully implemented other filtered objects in my project, but there seems to be a mistake in this particular scenario.

Answer №1

  1. Loop through each CalendarModel item and merge the CalendarEvent objects into an array using .reduce().

  2. Filter the CalendarEvent events based on their type and date.

getAllEvents: Signal<CalendarEvent[]> = computed(() =>
  this.dataService.allInformation()
    ?.allCalendarInformation
    ?.reduce(
      (acc: CalendarEvent[], cur: CalendarModel) => [...acc, ...cur.events],
      [] as CalendarEvent[]
    )
    .filter(
      (event: CalendarEvent) =>
        event.type === 'event' &&
        event.date &&
        new Date(event.date).getTime() >= new Date().setHours(0, 0, 0, 0)
    ))
);

Try out the demo on StackBlitz

Answer №2

The reason for this is that the filter method works on CalendarModel, which is a nested array. To filter it properly, you need to reduce or map the array to a single dimension first.

Once you have flattened the array, you can easily filter objects by their type property.

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

Transform a continuous string into an associative array with multiple dimensions

I am facing a challenge where I need to extract values from a string without any delimiting characters and create an associative array out of it. Let's take a look at an example string: *01the title*35the author*A7other useless infos*AEother useful i ...

Seeking assistance with repairing a pixelated image in matlab. Assistance required

https://i.sstatic.net/sCNy1.png Hello, I'm in need of assistance with fixing this image using for loops. I understand that I need to first detect the faulty pixels and then replace them. Thank you. By the way, I am a beginner in using matlab. clear ...

Find the two numbers within a specific range in an array using jQuery

I have two arrays and I need to check for any duplicate ranges. How can I achieve this? let startingArray = ['1', '6.1', '10', '31','6.2',3]; let endingArray = ['2', '9.9', '30&ap ...

The specified type `Observable<Pet>&Observable<HttpResponse<Pet>>&Observable<HttpEvent<Pet>>` is not compatible with `Observable<HttpResponse<Pet>>`

I'm currently attempting to integrate the Angular code generated by openapi-generator with the JHipster CRUD views. While working on customizing them for the Pet entity, I encountered the following error: "Argument of type 'Observable & ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

Updating the value of a key in an object is not functioning as expected

There is a single object defined as requestObject: any = { "type": 'type1', "start": 0, "size": 10, "keywords": ['abcd','efgh'], filters: [], } Next, attempting to change the value for keyword, I updat ...

Encountering a Typescript error when defining a curried function after an uncurried function

Upon placing the uncurried definition of a method above the curried definition, I encountered an error stating: Expected 1 arguments, but got 2.ts(2554). The dtslint test that failed reads as follows: function match(regExpression: RegExp, str: string): st ...

Adjust the tooltip position on the Mat paginator

I'm attempting to adjust the positioning of the tooltip for mat-paginator so that it is closer to the pagination buttons. Currently, the tooltip is positioned too far away, as shown below: https://i.sstatic.net/XYD1j.jpg I've made attempts to m ...

What is the step-by-step process for implementing tooltips in Ant Design Menu after version 4.20.0?

According to the Ant Design documentation: Starting from version 4.20.0, a simpler usage <Menu items={[...]} /> is provided with enhanced performance and the ability to write cleaner code in your applications. The old usage will be deprecated in th ...

A TypeScript interface creating a type with optional keys of various types while enforcing strict null checks

I am attempting to devise an interface in typescript that resembles the following: type MoveSpeed = "min" | "road" | "full"; interface Interval { min?: number, max?: number } interface CreepPlan { [partName: string] : Interval; move?: MoveSpe ...

What methods are available to me for creating a wrapper for an Angular Component that simply changes the component selector name?

Having experience with React, you can simplify a library component in your app by giving it a new name like this: const MyAppTable = (props) => <LibraryTable ...props />; I'm interested in achieving a similar result in Angular, but I'm ...

The occurrence of a loading error arises when attempting to load the second component, displaying the message 'The template instructed for component SidebarComponent is

My journey with Angular has just begun, and I decided to challenge myself by creating a simplistic dashboard. In order to achieve this, I developed two components called DashboardComponent and SidebarComponent. The DashboardComponent loads smoothly witho ...

Converting a string into a Date in Typescript while disregarding the timezone

Upon receiving a date in string format like this (e.g.): "11/10/2015 10:00:00" It's important to note that this is in UTC time. However, when creating a Date object from this string, it defaults to local time: let time = "11/10/2015 10:00:00"; let ...

Can you explain the purpose of this TypeScript code snippet? It declares a variable testOptions that can only be assigned one of the values "Undecided," "Yes," or "No," with a default value of "Undecided."

const testOptions: "Undecided" | "Yes" | "No" = "Undecided"; Can you explain the significance of this code snippet in typescript? How would you classify the variable testOptions? Is testOptions considered an array, string, or another d ...

Navigating through an interface array using *ngFor in TypeScript

After successfully implementing an interface to retrieve data from a service class, I encountered an issue when attempting to iterate through the FilteredSubject interface array. Despite using console.log, I was unable to achieve the desired outcome. You ...

Switching between rows in a table once information has been added to an array | Vue

I'm currently working on creating a table with rows that toggle when a 'View' button is clicked. The table is generated using a for loop for an array. I've successfully implemented the toggling functionality for preloaded data, but enco ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...

Retrieve information from a document and save it to a collection of data structures

I am currently working on developing a program that can read data from a file and store it in an array of structs. The program will then be able to calculate various statistics such as highest, lowest, average, and standard deviation. Right now, my main fo ...

Is it possible to generate a property for an interface by casting a key within a for-in loop?

When I attempt to set a property on an object with a value from a dynamically generated form, I utilize a for-in loop to identify a property in the object and assign it. FormFeatureArray.forEach((el) => { // form handling stuff omitted For(c ...

Traversing through Object consisting of dual arrays within VueJS

Currently, I am working on a chat application built in VueJS and encountering an issue when attempting to display messages along with their respective timestamps. The challenge arises from the need to iterate through an object that contains two arrays: one ...