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

Angular neglects the specified animation timing

I created a sidebar component that relies on the sidebarExpanded state passed through Input(). Despite the correct animation trigger upon input change, the width adjustment happens abruptly. Interestingly, the same animation code works flawlessly in anothe ...

Modifications to the toolbar styling are made by the Angular Material mat-form-field

Having some trouble creating an input field in my component alongside a mat-toolbar element. When I try to insert a mat-form-field, it ends up messing with the styling of the mat-toolbar. I've been unable to pinpoint exactly where the issue lies (if ...

Is TypeScript necessary, or can I simply stick with ES6?

As a client developer using AngularJS in my daily job, we are considering transitioning to TypeScript. After researching TypeScript, I discovered that most JavaScript packages I require need definition type files. This can be inconvenient, especially whe ...

When it comes to rendering components in React using multiple ternary `if-else` statements, the question arises: How can I properly "end" or "close" the ternary statement?

I have developed a straightforward component that displays a colored tag on my HTML: import React, {Component} from 'react'; import "./styles.scss"; interface ColorTagProps { tagType?: string; tagText?: string; } /** * Rende ...

The Ionic Keyboard close event does not trigger

I am attempting to automatically hide the keyboard when the user scrolls within the app. Here is my code snippet: .html <ion-content class="maincontent" (ionScrollStart)="scrollStart()"> <router-outlet></router-outlet> </ion-conten ...

Definitions for nested directories within a main index.d.ts

We have developed custom typings for the latest version of material-ui@next and successfully included them in the library during the last beta release. For those interested, you can access the index.d.ts file here. However, there seems to be a problem wi ...

Typescript input event

I need help implementing an on change event when a file is selected from an input(file) element. What I want is for the event to set a textbox to display the name of the selected file. Unfortunately, I haven't been able to find a clear example or figu ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

Angular `CORS` Ailment

I am currently utilizing the MEAN stack (MongoDB, Express, Angular, and NodeJS). I have a basic function for fetching data from an external API as shown below: let api = 'https://thongtindoanhnghiep.co/api/city'; return this.http.get<any>(a ...

When using the ionic 3 storage.get function, it may return a null value when accessed outside

In regards to storage, the function is returning a null value outside of the function. Below is the code snippet: username:any; this.storage.get('user').then((value) => { this.username = value; }); console.log(this.username); Ou ...

The identifier 'id' is not recognized within the 'never' type in Angular

Hello there, I am currently working on a small project for a store website. You can find the project here. However, I have encountered an issue when trying to move items to the cart. Specifically, in the source code file app/components/product-list/produc ...

Tips for implementing type safety in a generic class to verify that the response type aligns with the anticipated type in TypeScript

In TypeScript, I have created a QueryFactory class with two generic type parameters: TQuery and TResponse. My goal is to ensure type safety so that if the TResponse type does not match the expected response type of the TQuery type, the compiler will throw ...

Find the combined key names in an object where the values can be accessed by index

I am currently working on creating a function called indexByProp, which will only allow the selection of props to index by if they are strings, numbers, or symbols. This particular issue is related to https://github.com/microsoft/TypeScript/issues/33521. ...

Error in Angular ESLint: The key parameter is mandatory

I'm attempting to download a file using the Angular code below, but I consistently receive an error stating Parameter "key" required const headerValues = new HttpHeaders({ 'Content-Type': contentType!, 'Accept': contentTy ...

Add CSS properties to child elements that are not of a specific selector, while styling their descendants without any restrictions

Seeking assistance for an Angular application, but the query also pertains to CSS principles in general. In my Angular project, I have a main component containing several child components, all with standard view encapsulation. Specifically, I am looking t ...

The result should display the top 5 application names based on the count property found within the ImageDetails object

data = { "ImageDetails": [ { "application": "unknownApp, "count": 107757, }, { "application": "app6", "count": 1900, }, { & ...

Error in Angular Services due to Circular Dependency

I am encountering the following error message: Provider parse errors: Cannot instantiate cyclic dependency! Within my code, I have a Component dedicated to making HTTP calls to my backend server: backend.component.ts import { Http } from '@angul ...

Issue with Angular data display in template

My Ionic app with Angular is fetching data in the constructor, but I am facing difficulties displaying it in the HTML. Code component receiver: any; constructor( //.... ) { // get receiver data const receiverData = this.activatedRoute.snapsho ...

The correct way to implement the bootstrap carousel with Angular

Among the multitude of inquiries on stackoveflow, I delved into a few: How to implement bootstrap carousel with Angular ng-repeat? How to utilize carousel with Angular : No answers after 9 months. Issues with Slides in Bootstrap Carousel... : No satisfac ...

Best practice for integrating Typescript into an established ASP.NET 4 Webforms project

Currently, I am working on an older asp.net 4.0 Webforms project using Visual Studio 2015. My goal is to transition from using Javascript to TypeScript for certain client side code tasks. While I have experience using TypeScript in projects outside of Vis ...