Ways to categorize items retrieved from an HTTP request to the backend in Angular

When making a call to the backend using this http request:

this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => {
  this.studentObject = values;
});

The studentObject is structured as shown below:

{
    records: [{name: james, school: USC, .....}, {name: Micheal, school: UCLA, ......},{name: 
         John, school: UCLA, ......}],
    size: 3
}

I am interested in organizing the schools and adding a count before integrating it into the studentObject. This would result in an object similar to:

[{school: UCLA, count: 2}, {school: USC, count: 1}]

Answer №1

Here is an example of using the groupBy operator:

data$ = this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/));

schoolsGrouped$ = data$.pipe(
     concatMap(students => students),
     groupBy(student => student.school),
     mergeMap(group =>
       zip(of(group.key), group.pipe(toArray())).pipe(
         map(([key, students]) => ({ key, students }))
       )
     ),
     toArray()
   );

You can access the grouped data like this:

  constructor() {
    this.schoolsGrouped$.subscribe(schools => 
      schools.forEach(school => console.log(school.key, school.students.length)))
  }

Check out a working example here.

To integrate the grouped info into your existing data structure:

  schoolsGrouped$ = of(this.data.records).pipe(
    concatMap(students => students),
    groupBy(student => student.school),
    mergeMap(group =>
      zip(of(group.key), group.pipe(toArray())).pipe(
        map(([key, students]) => ({ key, students }))
      )
    ),
    tap(
      school =>
        (this.data = {
          ...this.data,
          schools: [
            ...this.data.schools,
            { school: school.key, count: school.students.length },
          ],
        })
    ),
    toArray()
  );

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 transfer Material-UI FlatButton CSS to a different Button element

I've recently incorporated a loading button object into my website from (https://github.com/mathieudutour/react-progress-button), and now I want to customize it using the Material-UI FlatButton CSS. However, I'm not quite sure how to achieve this ...

How to conceal the side navigation bar on specific pages or components within an Angular application

Currently immersed in developing a web application with Jhipster and Angular. I've managed to set up a side navbar along with a top navbar on every page. However, I'm struggling to hide the side navbar on specific pages and could use some guidanc ...

Changing the color of a single child object in Threejs

Hey there, I'm facing an issue with changing the color of a specific element in my 3D Model (imported using the GLTFLoader). I've included some images showcasing the model's structure. The element I'm trying to target is the one highli ...

Tips for preventing recursion when utilizing scrollIntoView() in a scroll event handler

My goal is to break down my website into screen-sized sections that automatically scroll to the next section when a user begins scrolling. I attempted to accomplish this by using the following code: $(window).scroll(function() { getElementToScroll().s ...

Removing Angular Template space highlights in WebStorm can be done easily with a few simple steps

Is there a way to remove space highlights in Angular / TypeScript using WebStorm 2019? https://i.stack.imgur.com/vfudR.jpg Many thanks, Sean ...

What is the process for transferring a Pulumi Output<T> to the container definition of a task in ECS?

When creating a generic ECS service that deals with dynamic data, it is important to note that the containerDefinition within a Task Definition must be provided as a single valid JSON document. The code snippet for this setup looks like: genericClientServi ...

Issues with Socket.io in receiving messages on the client side

I've been experimenting with websocket testing in Angular and Nestjs by following this tutorial. This is the gateway component from my Nestjs project. import { SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse, MessageBody } f ...

Issue with arrow function not being invoked in a React TypeScript component's prop inside a function

My parent component holds a useState hook to determine if the mobile Nav is open or closed: const [showMobileMenu,setShowMobileMenu] = useState<boolean>(false);. To close the mobile menu, I created an arrow function and passed it down to a child comp ...

Saving a revised JSON file using AngularJS

Currently, I am in the process of developing a phonegap application using AngularJS that relies on a .json file to store an array of entries. The main goal I am aiming for is to enable users to mark specific entries as favorites and then utilize that data ...

Ways to set the minimum width of a div depending on its contents

As I work on my website, I encountered an issue with a div containing a table. The div expands to full width, but when I resize the screen, it shrinks causing the content to overlap. I am looking for a solution where the minimum width of the div adjusts b ...

Does the Node Schedule library create new processes by spawning or forking them?

Is the node-schedule npm module responsible for spawning/forking a new process, or do we need to handle it ourselves? var cron = require('node-schedule'); var cronExpress="0 * * * *"; cron.scheduleJob(cronExpress, () => { //logger.info(" ...

The addition and deletion of classes can sometimes lead to disruptions in the DOM

I've been struggling to phrase this question for a while now. I'm working on a single-page e-commerce site that operates by modifying the HTML in divs and using CSS along with JQuery to show and hide those divs. My problem arises when, occasional ...

Achieving dynamic height in a parent div with a sticky header using mui-datatables

Here are the settings I've configured for my mui-datatables: const options = { responsive: "standard", pagination: false, tableBodyHeight: '80vh', }; return ( <MUIDataTable title={"ACME Employee ...

Modifying a gridview cell through a Modal popup that is displayed using the rel attribute

I have successfully implemented a modal dialog using CSS and the rel="#showEditModal" attribute of a button. This enabled me to add values to the database and update the gridview effectively. However, I am now facing a challenge where I need to be able to ...

Utilizing Axios: Maintaining session continuity post successful authorization and including it in subsequent requests - testing in a browser-less environment

During this test scenario, I am sending an axios post request to an ExpressJS server that is running with passportjs local. The request includes a userId and password, and the server responds with a status code of 200, along with setting an appropriate hea ...

Initiate the process of displaying data on a datetime chart using Highcharts

I am currently developing a yearly chart, but I've encountered a small issue. The chart begins in January, however there is no data available until May. The client specifically wants the chart to only display when there is data available, and unfortu ...

Issue between Promise and EventEmitter causing race conditions in ExpressJS

Currently, I am working on a NodeJS/Express web application where users can upload files that are then parsed using the connect-busboy module and saved to a database with Sequelize. Once the data is stored, I aim to redirect the user to a specific page. Ho ...

Is there a way to modify the package version with yarn, either upgrading or downgrading?

Is there a way to downgrade the version of a package using yarn's "dependencies" feature? ...

The e.currentTarget attribute in Material UI buttons is a key element that

I am facing an issue with implementing three tabs and buttons in my project. Each button should display a corresponding message when selected I have tried using e.currentTarget but no success so far. Can someone guide me on how to resolve this problem? You ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...