What is the best approach to organize data from an observable based on a nested key?

I'm currently developing a new application and struggling with grouping data. The data is being pulled from an observable, and I need to group objects by their status and push them into an array. I attempted to use the groupBy() method, but unfortunately, it did not produce the desired results.

Here is a snippet of what I have:

const data = [
  {
    id: 3424234,
    name: "asdfgasdgas",
    protocol: 235452345,
    status: {
      code: "AVAILABLE",
      displayName: "Available"
    }
  },
  {
    id: 543534,
    name: "regertjerg",
    protocol: 7745672345,
    status: {
      code: "AVAILABLE",
      displayName: "Available"
    }
  },
  {
    id: 96089678,
    name: "kluioliudas",
    protocol: 7878745,
    status: {
      code: "INITIALREVIEW", 
      displayName: "Initial review"
    }
  }
] 

Now, this is how I envision the data grouped:

const result = [
  {
    code: "AVAILABLE",
    displayName: "Available",
    items: [
      {
        id: 3424234,
        name: "asdfgasdgas",
        protocol: 235452345
      },
      {
        id: 543534,
        name: "regertjerg",
        protocol: 7745672345
      }
    ]
  },
  {
    code: "INITIALREVIEW", 
    displayName: "Initial review",
    items: [
      {
        id: 96089678,
        name: "kluioliudas",
        protocol: 7878745
      }
    ]
  }
]

Your assistance in solving this challenge is greatly appreciated!

Answer №1

Utilizing the reduce() function can help achieve this outcome:

outcome = information.reduce(function (r, a) {
        r[a.condition.key] = r[a.condition.key] || [];
        r[a.condition.key].push(a);
        return r;
    }, Object.create(null));

This process involves categorizing by the status.code

Answer №2

Here is a suggestion for you:

 

const data = [ { id: 3424234, name: "asdfgasdgas", protocol: 235452345, status: { code: "AVAILABLE", displayName: "Available" } }, { id: 543534, name: "regertjerg", protocol: 7745672345, status: { code: "AVAILABLE", displayName: "Available" } }, { id: 96089678, name: "kluioliudas", protocol: 7878745, status: { code: "INITIALREVIEW", displayName: "Initial review" } } ] 

const groupBy = (arr) => data.reduce((acc, ele)=>( (acc[ele.status.code] = acc[ele.status.code] || []).push(ele), acc),{})

const reformat = ([k, v]) => ({code: k, displayName: v[0].status.displayName, items: v.map(({id, name, protocol})=>({id, name, protocol}))})
  
// Use the groupBy function to categorize the data based on status code
const result  =  Object.entries(groupBy(data)).map(ele=> reformat(ele))

console.log(result);
 

Answer №3

This could be a simple and clear solution.

let uniqueCodes = [];
let uniqueStatuses = [];
data.forEach(item => {
    if(!uniqueCodes.find(code => code === item.status.code)) {
        uniqueCodes.push(item.status.code);
        uniqueStatuses.push(item.status);
    }
})
let finalResult = uniqueStatuses.map((status:any) => {
    status.items = data.filter(element => element.status.code === status.code)
    return status;
})
console.log(finalResult)

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 call to 'setRequestHeader' on 'XMLHttpRequest' was unsuccessful due to the object's state not being OPENED

While developing an angular application with a restful API get(), I encountered a few errors such as unauthorization error:401 which I managed to resolve. However, now I am facing another error that seems quite straightforward. I even tried adding the CORS ...

After I deploy my Next.js code to Vercel, including Google Analytics added by @next/third-parties, I am encountering an error that does not appear in development mode

Lately, I completed a next.js project and integrated Google Analytics using @next/third-parties/google. During development, everything worked perfectly, but upon deploying it to vercel.com, an error popped up. ` ./app/layout.tsx:3 ...

Angular-cli is throwing an error stating it cannot locate the module '@ngtools/json-schema'

After running npm update in my project, I seem to be encountering an issue whenever I try to run ng serve. Error: Cannot find module '@ngtools/json-schema' Oddly enough, the @ngtools file is clearly present in my node_modules directory. I&apo ...

The issue of the list view button not responding to click events in Angular2 NativeScript

I have been working on implementing an onclick event for a listview item button. Below is the code snippet that I have tried, but unfortunately the console log is not being triggered when the button is clicked. I am unsure of what the problem might be in ...

Tips on customizing the appearance of the dropdown calendar for the ngx-daterangepicker-material package

Is there a way to customize the top, left, and width styling of the calendar? I'm struggling to find the right approach. I've been working with this date range picker. Despite trying to add classes and styles, I can't seem to update the app ...

Generating typescript definitions for Polymer 2.4 packages

According to information provided in the latest announcement, declarations are now automatically generated from the Polymer source. I recently upgraded to Polymer 2.4 and encountered an error during project build due to a missing typescript definition fil ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

Authentication for file uploads in Angular 2 using Dropzone and passportjs

I am currently working on implementing authentication for an admin user using Express, Passport, and MySQL in a specific page. The authentication process works fine, but I am facing an issue with verifying whether the user is logged in while uploading file ...

Creating a custom React hook in TypeScript to handle mouse events

I have been working on creating a custom hook in TypeScript/React, and I am looking to convert the code snippet below into a custom hook. Currently, I am passing handleClick to the onClick attribute in a div element to detect user clicks and route them to ...

Bespoke Socket.io NodeJS chamber

I am currently developing an application involving sockets where the requirement is to broadcast information only to individuals within a specific room. Below is a snippet of the code from my server.ts file: // Dependencies import express from 'expre ...

There seems to be an issue with the useReducer value not updating when logging it in a handleSubmit function

I'm currently incorporating useReducer into my Login and Register form. Interestingly, when I attempt to log the reducer value, it only displays the default value. However, if I log it within the useEffect hook, it functions correctly. Below is a sn ...

What is the method for reaching a service in a different feature module?

Currently, I am utilizing Angular 2/4 and have organized my code into feature modules. For instance, I have a Building Module and a Client Module. https://i.stack.imgur.com/LvmkU.png The same structure applies to my Client Feature Module as well. Now, i ...

Creating a composite object in Angular 2 reactive forms: a step-by-step guide

These are the two classes I have: export class Machine { name = ''; computer = new Computer() } export class Computer { os = ''; } Then in my component, using reactive forms, I have: ngOnInit() { this.form = this.fb ...

Error: monaco has not been declared

My goal is to integrate the Microsoft Monaco editor with Angular 2. The approach I am taking involves checking for the presence of monaco before initializing it and creating an editor using monaco.editor.create(). However, despite loading the editor.main.j ...

Compilation issues in node-modules arise following the Vue package and i18next updates

Recently, I decided to upgrade from the i18n package to the newer version called i18next in my project. However, this update led to numerous errors popping up during compilation. Fortunately, by adding 'skipLibCheck' to the compiler options in th ...

Secure mustache templates for data validation

Is there a method to achieve the following?: my-custom-template.mstach Hello {{name}}! script.js import { readFileSync, writeFileSync } from 'fs'; import * as Mustache from 'mustache'; export interface Person { name: string; } ...

RxJS pipe operation ignoring observable

Currently, I am in the process of transitioning an app from Promises to RxJS and I could use some guidance on whether I am heading in the right direction. Situation: I have a ModalComponent that appears when an HTTP request is sent and disappears once the ...

In the process of using SWRInfinite for React Infinite Scrolling, the initial call may be made

Can someone help me understand why my useGetItems hook, which imports the usePagination hook, keeps repeating the first call history every time I scroll? /items?_page=1&_limit=40 /items?_page=1&_limit=40 /items?_page=2&_limit=40 /items?_page=1 ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

"Encountered the error message 'ViewContainerRef provider not found' when working with an ng-packagr component

I have utilized angular cli to create a components library by using the command ng generate library. In this library, there is a component that implements *ngIf within a module. Upon successfully building and installing the library into my main project, I ...