Define the state of an object using Parent and Children classes following the application of a filter

Within Angular 8, I am dealing with an Observable:

let parents: Observable<Parent[]>;

The classes Parent and Child are defined as follows:

class Parent {
  id: number;
  name: string;
  children: Child[];
}

class Child {
  id: number;
  name: string;
}

My goal is to locate the specific Child whose id value is 1 across all children of the parents.

Following that, I must establish a condition involving that particular Child and its respective Parent ... I attempted it like this:

  parents.pipe(
    map(parents => parents.map(parent => parent.children)),
    map(children => children.find(child => child.id == 1))
    map(child => Test Condition with resulting Child and its Parent 

A challenge arose when I discovered that the variable children in the line map(children => is of type Child[][] rather than Child[], causing the expression child.id to fail due to child being of type Child[].

Additionally, in the final map function, I require not only the Child object but also its associated Parent in order to construct the condition and return an Observable<boolean>

Is there a way to accomplish this? Is it impossible using map?

Answer №1

Here is a recommended solution:

parents.pipe(
    map(parents => parents.map(parent => parent.children).flat()),
    map(children => children.find(child => child.id == 1)),
    map(child => Evaluate Test Condition with the resulting Child and its Parent)

Answer №2

To solve this issue, utilize the flatMap function by visiting https://rxjs-dev.firebaseapp.com/api/operators/flatMap. This will allow you to combine all children-lists into a single long list for further processing.

Try implementing the following solution:

const childrenWithId1: Children[] = parents.pipe(
    flatMap(parent => parent),
    flatMap(child => child.children),
    filter(child => child.id == 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

Ways to set a button as default clicked in an Array

I have a collection that stores languages and their boolean values. My goal is to automatically set buttons to be clicked (active) for each language with a true value in the collection. Whenever a different language is selected by clicking on its respect ...

Organizing Firebase functions: Managing multiple functions and dependencies

Objective I aim to gain a deeper understanding of how the firebase CLI manages the deployment process for multiple firebase functions, each stored in different files, and how it handles dependencies that are specific to certain functions. Situation If I ...

Encountering a problem while bringing in screens: 'The file screens/xxx cannot be located within the project or any of these folders.'

I am currently working on an iOS application using React Native technology. During the process of importing a specific screen, I encountered an error message. Can anyone provide guidance on how to resolve this issue? Error: Unable to resolve module scree ...

Guide to building a nested dropdown navigation in Angular 12 with the power of Bootstrap 5

I am looking to implement a multilevel dropdown feature in my Angular 12 project with Bootstrap 5. Can someone please guide me on how to achieve this? For reference, you can view an example here. Thank you in advance! ...

How can I sort by the complete timestamp when using the Antd table for dates?

I have an item in my possession. const data: Item[] = [ { key: 1, name: 'John Brown', date: moment('10-10-2019').format('L'), address: 'New York No. 1 Lake Park', }, { ...

How can I display an array in reverse order using *ngFor in a template?

Just starting out with Angular and I'm looking to display an array in reverse order. Here's what I have: <ng-container *ngFor="let user of _users.reverse(); let i = index"> <tr> <td>{{ _users[i].firstN ...

Promise disregards the window being open

I'm facing an issue with redirecting users to Twitter using window.open in a specific function. It seems like the instruction is being ignored, even though it works perfectly on other pages. Any ideas on how to fix this? answerQuestion() { if ...

The JSON representation is not appearing for the newly introduced nested components

Building a nested component within another component and implementing two-way binding for dynamically added field values using the JSON pipe in the view. However, encountering an issue where the newly added values are not reflected in the JSON view. If yo ...

Is Angular File API Support Compatible with HTML5?

When checking for HTML5 File API browser support in my code: private hasHtml5FileApiSupport; constructor(@Optional() @Inject(DOCUMENT) document: Document) { const w = document.defaultView; this.hasHtml5FileApiSupport = w.File && w.FileReader & ...

Removing sourceMappingURL from an Angular Universal build: A step-by-step guide

Using this repository as my foundation, I have successfully resolved most of the plugin errors except for one that continues to elude me. It's puzzling because no other plugin anticipates a .map file in an SSR build since it is intended for productio ...

Error: React is throwing a SyntaxError because a ")" is missing in the argument list

While working on a React-typescript project using Vite, I encountered an issue where my page was displaying blank and showing the error : Uncaught SyntaxError: missing ) after argument list (at main.tsx:6:51) This error was found in the main.tsx file : im ...

Properly passing props to child components in React with TypeScript. Resolve Error ts(2322)

I am facing an issue where my code works perfectly in Javascript, but encounters problems when converted to Typescript. Despite the complexity of the question, it actually boils down to a simple query. I just wanted to share the functional JS code as a sol ...

Enhancing a component with injected props by including type definitions in a higher-order component

Implementing a "higher order component" without types can be achieved as shown below: const Themeable = (mapThemeToProps) => { return (WrappedComponent) => { const themedComponent = (props, { theme: appTheme }) => { return <Wrapped ...

MongoDB NextJS connection issue "tried to retrieve a connection from a closed connection pool"

I am attempting to establish a connection to my MongoDB database in order to retrieve some information. When setting up the connection without fetching any data, everything works fine. However, when trying to fetch data, the console throws this error: at ...

Having an extensive amount of mat-tooltip components within a mat-table can cause a decrease in

Our team has been utilizing the mat-table grid implementation, with a mat-tooltip for each cell. It seems that the tooltip renders for every cell, regardless of whether the user hovers over it or not. Below is a snippet of the code showcasing the tooltip u ...

The compiler is unable to locate the node_module (Error: "Module name not found")

Error: src/app/app.component.ts:4:12 - error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try npm i @types/node and then add node to the types field in your tsconfig. 4 moduleId: module.id, When att ...

Issues have arisen with the functionality of Ionic2-Calendar on the device

I'm currently working on a project that involves developing an Ionic 4 app with Angular 8. I've encountered a peculiar issue while using this calendar plugin. It seems similar to the problem discussed in this thread. Despite reaching out for sol ...

Setting the selected value of a radio button in an edit form: a step-by-step

I'm currently developing an edit form using ReactiveFormModule. My goal is to display data in the edit form with various input elements such as textboxes, dropdowns, radio buttons, and checkboxes. I've been successful in setting values for textbo ...

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

combine string inputs when ng-click is triggered

Is there a way to pass a concatenated string using ng-click to MyFunction(param: string)? I have tried but so far, no luck: <input id="MeasurementValue_{{sample.Number}}_{{$index}}" ng-click="Vm.MyFunction('MeasurementValue_{{sample.Number ...