Exploring the utilization of grouping keys within the GroupBy operator in RxJS

After receiving a structured response from an API,

I come across the following signature:

methodApi(): Observable(Array<MyClass>)

The data looks like this:

{ id: 1, name: 'Red', parentId: null }
{ id: 2, name: 'Apple', parentId: 1 }
others

My goal is to group this data by parentId.

methodApi()
.pipe(groupby((x: MyClass[] => ...))) // THIS IS WHERE THE ISSUE LIES
.subscribe(x => console.log(x));

The methodApi returns Observable<Array>. The problem arises when I attempt to reference the parentId property within the 'groupby' method since it requires an array as input and not a specific object like MyClass.

How can I effectively resolve this grouping issue?

Running Angular 9.0 with RxJS 6.5.5

Answer №1

To transform your array into an observable stream, you can utilize the from method to create a new stream. Then, by using groupBy, you can group the items based on a specific criteria before converting it back into an array:

methodApi().pipe(
  concatMap((result) => from(result)),
  groupBy((item) => item.parentId),
  mergeMap(group => group.pipe(toArray()))
).subscribe(x => console.log(x));

Check out this example

Alternatively, you can also achieve the same result using mergeAll:

methodApi().pipe(
  mergeAll(),
  groupBy((item) => item.parentId),
  mergeMap(group => group.pipe(toArray()))
).subscribe(x => console.log(x));

See this example for reference

Answer №2

To achieve this, you can utilize the groupBy operator in the following manner:

methodApi().pipe(
  groupBy((item) => item.parentId),
  mergeMap(group => group.pipe(toArray()))
).subscribe(console.log) // This code snippet will provide you with an array grouped by parentId

Answer №3

The functionality of the RxJs group by operator is being misunderstood in this context. Instead of grouping objects emitted by the stream, the goal here is to group items within an array that is also emitted by the stream. To achieve this, a custom group by function tailored for arrays, rather than observables, is required. A simple solution would involve using a reduce method to organize the items into an object structure with the parentId serving as the key.

methodApi()
.pipe(map(results => results.reduce(
  (group, item) => {
    if (group[item.parentId]) {
      group[item.parentId].push(item);
    } else {
      group[item.parentId] = [item];
    }
    return group;
  }, {})
)).subscribe(group => {});

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

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

The JSON file I am trying to load is encountering a parsing failure over HTTP

When trying to load valid json data, I encountered the following error message: Check it out on StackBlitz! Error: Http failure during parsing for ... .json https://i.sstatic.net/hG4uQ.jpg recipe.component.ts url = '../../files/recipes.json&ap ...

Discovering the type in Typescript without explicitly defining a type variable for the callback

I am looking for a solution to wrap rxjs subscribe's next callback with my own function: type Handler<T> = (value: T) => void; export function withTryCatch<T>(callback?: Handler<T>): Handler<T> { return (value: T) => ...

What is the best way to experiment with transclusion (ng-content) in Angular2?

I have a specific component that I need to test, here is the code: import {Component, OnInit, Input} from "@angular/core"; @Component({ selector: 'column', template: '<ng-content></ng-content>', host: { ...

Could someone assist me in identifying the issue with this logfile and guiding me in the correct direction?

Can someone help me troubleshoot the ng e2e issue in my code? Here's a screenshot of the log file: https://i.sstatic.net/PCrab.png I apologize for the formatting of the package.json file. `package.json` file: { "name": "planning", "version": "0. ...

What are the distinctions between using getStaticPaths + getStaticProps and useRouter in NextJS?

I'm currently diving into the world of NextJS and finding myself puzzled by the distinctions between getStaticProps & getStaticPaths compared to utilizing useRouter().query. At this point, it appears to me that both methods serve a similar purpos ...

Is it feasible to determine the precise class of an object while utilizing a variable that possesses a union type in Typescript?

Currently delving into Typescript and running tests. Upon using console.log, I received an object. Given its typed nature, I anticipated it to accurately determine the type of variable c. interface Car { gears: number } interface Bike{ gears: number ...

Filtering with the Microsoft Graph Client

I am attempting to retrieve a comprehensive list of calendars owned by the user who is currently authenticated. The code below successfully retrieves calendars, but it does not specify that I want only those owned by the authenticated user. await this.gr ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

Hide a dialogue box by clicking outside of it

I am working on an Angular application that features a pop-up dialog for user input. I want the dialog to close or hide when the user clicks anywhere outside of it within the main application. This way, the user can input data without interruptions, and th ...

Attention: certain content may have been removed due to HTML sanitation

Hi there, I'm currently working on incorporating a search bar into a modal window by embedding HTML within the modal body. Here's how I've written the code: onClick() { const dialogRef = this.modal.alert() .size('lg' ...

Troubleshooting: encountering empty page after deploying Angular 5 with .NET Core Web API

After attempting to deploy both an Angular 5 app and a .NET Core Web Api to the same server (IIS with .NET Core bundle), I encountered a frustrating issue where only a blank page would display upon starting up the application. Surprisingly, there were no c ...

Typescript: The property isComposing is not found on Event type

While working on a React app with Typescript, I encountered a Typescript error both during compile time and in the editor: TS2339: Property isComposing does not exist on type Event This issue arises when handling an OnChange event in an HTML Input element ...

Assistance with debugging Angular 2 alongside Express in Visual Studio Code

I have been attempting to configure a debugger in Visual Studio Code for my TypeScript project, but I find myself stuck and frustrated. Let me provide you with an overview of my project structure: ├───.vscode ├───dist │ ├───cli ...

Angular Error Handler - Extracting component context information from errors

In the event of a TypeScript error, I am looking to send all of the component's attribute values to a REST API. It would greatly benefit me if I could access the component's context (this) in order to retrieve the values of all attributes within ...

Utilizing *ngfor in Angular 7 to Group and Display Data

I currently have incoming data structured like this in my Angular application Visit this link to see the data format https://i.stack.imgur.com/jgEIw.png What is the best way to group and sort the data by State and County, and present it in a table as sh ...

Obtaining access to a FormGroup instance when connected to a <form> through a directive

Question about HTML Form Directive <form [formGroup]="form"> <input type="text" formControlName="name" class="form-control" /> <div *errorFeedback name="name" class="error-feedback"></div> </form> Exploring Form Directiv ...

Using TypeScript to work with asynchronous child_process.exec operations

Having trouble implementing a child_process.exec call with TypeScript and finding error handling to be quite challenging. Here's the basic idea of what I'm attempting: import { promisify } from "util"; import { exec, ExecException } fr ...

There was an issue with reading the properties of an undefined object due to a TypeError. The specific property being read was 'native

After updating the dependencies in my package.json to their latest versions, I noticed that the site I'm working on, which displays various graphs and charts, started to encounter issues. Prior to the update, everything was functioning properly withou ...

Is there a way to transform time into a percentage with the help of the moment

I am looking to convert a specific time range into a percentage, but I'm unsure if moment.js is capable of handling this task. For example: let start = 08:00:00 // until let end = 09:00:00 In theory, this equates to 100%, however, my frontend data ...