Grouping JavaScript nested properties by keys

I have a specific object structure in my code that I need to work with:

{
    "changeRequest": [{
            "acrId": 11,
            "ccrId": "",
            "message": "test message"
        },
        {
            "acrId": 12,
            "ccrId": "123456",
            "message": "Car Generation successful."
        }
    ],
    "assessmentDetails": [{
            "qId": 1749
        },
        {
            "crList": [{
                "compName": "Chevrolet Cobra",
                "cId": "169576",
                "acrId": 11
            }],
            "qId": 1737
        },
        {
            "qId": 1738,
                "crList": [{
                "compName": "Ferrari",
                "cId": "169586",
                "acrId": 11
            }],
        },
        {
            "crList": [{
                    "compName": "Mercedez Benz",
                    "cId": "169575",
                    "acrId": 12
                },
                {
                    "compName": "Isdera",
                    "cId": "169577",
                    "acrId": 12
                }
            ],
            "qId": 1739
        }
    ]
}

Currently, I am using Angular and the ngFor directive to iterate through the changeRequest array to display either the ccrId if not empty or the message if it is. However, I now have a requirement to group the component names based on the acrId and display them as a nested list.

The expected output should look like this:

<ol>
  <li>
    test message
    <ul>
      <li>Chevrolet Cobra</li>
      <li>Ferrari</li>
    </ul>
  </li>

  <li>
    123456
    <ul>
      <li>Mercedez Benz</li>
      <li>Isdera</li>
    </ul>
  </li>
</ol>

This grouping functionality needs to be implemented in both HTML and TypeScript files. Here is an example of how it can potentially be achieved:

HTML

<ol>
                    <ng-container>
                        <li *ngFor="let crObj of formatedBfaData">
                            <ng-container
                                *ngTemplateOutlet="crObj.crId ? displayCrLink : displayCrErrorMessage; context:{ $implicit: crObj}">
                            </ng-container>
                            <ng-template #displayCrLink let-crObj>
                                <div class="pb-2">{{ crObj.crId }}</div>
                            </ng-template>
    
                            <ng-template #displayCrErrorMessage let-crObj>
                                <div class="text-danger">{{crObj.name}}</div>
                            </ng-template>
                        </li>
                    </ng-container>
                </ol>

TS

this.formatedBfaData = data.changeRequest.map(crObj => {
        return {crId: crObj.ccrId !== '' ? crObj.ccrId: null, name: crObj.message}
      })

I would appreciate any guidance on how to properly implement the required grouping logic. Thank you!

Answer №1

For each crList, you can locate the one that corresponds to the desired acrId.

const data = {
    "changeRequest": [{
            "acrId": 11,
            "ccrId": "",
            "message": "test message"
        },
        {
            "acrId": 12,
            "ccrId": "123456",
            "message": "Car Generation successful."
        }
    ],
    "assessmentDetails": [{
            "qId": 1749
        },
        {
            "crList": [{
                "compName": "Chevrolet Cobra",
                "cId": "169576",
                "acrId": 11
            }],
            "qId": 1737
        },
        {
            "qId": 1738,
                "crList": [{
                "compName": "Ferrari",
                "cId": "169586",
                "acrId": 11
            }],
        },
        {
            "crList": [{
                    "compName": "Mercedez Benz",
                    "cId": "169575",
                    "acrId": 12
                },
                {
                    "compName": "Isdera",
                    "cId": "169577",
                    "acrId": 12
                }
            ],
            "qId": 1739
        }
    ]
};

const transformed = data.changeRequest.map(({ acrId, message }) => [message, data.assessmentDetails.filter(({ crList }) => crList).flatMap(({ crList }) => crList.filter((item) => item.acrId === acrId).map(({ compName }) => compName))]);

console.log(transformed)
console.log(Object.fromEntries(transformed))

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

What could be the reason my RxJS Observable chain does not run again when new emissions are made?

Currently, I am facing a unique challenge while working with RxJS in an Angular service. The issue revolves around two observable chains designed to enhance a stream of notifications with user data. One chain functions correctly, allowing for multiple trig ...

Combining two arrays of names and values into a fresh object using Javascript

Trying to merge two arrays, one for column headers: cNames = ["Year","Count"] And another for data: mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143] The goal is to combine them like this: [ { Year: "2005", Count: 5021 ...

How can I customize the <span> element created by material-ui?

Is there a way I can customize the appearance of the <span> tag that is produced when using the Checkbox component from the material-ui library? Essentially, I am seeking a method to alter: <span class="MuiButtonBase-root-29 MuiIconButton-root-2 ...

Is it possible to set up an automatic redirection to the Identity Provider sign-in page when accessing a protected page in Next.js using Auth.js?

Currently in the process of developing a web platform utilizing [email protected] and Auth.js([email protected]). The provider has been configured with the given code, allowing successful signing in using the "Sign in" button. auth.ts import Ne ...

Leveraging jest.unmock for testing the functionality of a Promise

I've implemented Auth0 for managing authentication in my React App. Below is the code snippet I am trying to test: login(username: string, password: string) { return new Promise((resolve, reject) => { this.auth0.client.login({ ...

Updating token (JWT) using interceptor in Angular 6

At first, I had a function that checked for the existence of a token and if it wasn't present, redirected the user to the login page. Now, I need to incorporate the logic of token refreshing when it expires using a refresh token. However, I'm enc ...

Retrieve the JSON data from an AJAX request

I am a beginner in the world of AJAX and JavaScript. In one of my projects, I need to retrieve a JSON object in my JavaScript file. I have utilized spray-json library which displays the JSON object at this URL: http://localhost:8081/all-modules { "statu ...

Issues with JQuery scroll() / scrollTop() functionality in Internet Explorer and Firefox

Our current script showcases a dotted line starting from the top of the screen leading to an up arrow. The position of the arrow changes based on how far the user has scrolled down the page, allowing them to click on the arrow and scroll back to the top. W ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

Node.js Implementation of HTML Content

Currently, I am attempting to iterate through a list of items and generate HTML code to be passed into the view file: const itemWrap = '<div id="items"></div>'; userDetails.notes.forEach(item => { const itemE ...

Employ the power of a static force layout to forge an intricate web of connections within the realm of

I have found a great network that works really well. It automatically updates the node position when the size of the window changes. Now, I want to make it fixed. What I mean by this is that I want to compute a certain number of ticks (let's call it ...

Warning: Node encountering unexpected Unhandled Promise Rejection ERROR

I've encountered a problem in my code that is triggering an UnhandledPromiseRejectionWarning in Node, but I'm struggling to understand the root cause. Here's a simplified version of the code: export class Hello { async good(): Promise<s ...

What is the best way to execute the angular-phonecat tutorial tests while the server is operating without a graphical user interface?

The angular-phonecat demo assumes that your server has chrome installed and you are running it there. When you run the command npm test, the local chrome browser should launch and continuously run the tests. However, if you are using a headless server li ...

Error message: Invalid form submission in Django REST framework

I am currently working with a model, model form and view structured in the following way: @api_view(['POST']) def addCigar(request): print(request.POST) form = CigarForm() if request.POST: form = CigarForm(request.POST) ...

What is the best way to utilize the "useRouter" function to extract parameters from the URL within the getServerSideProps() method in Next.js?

How can I access the URL parameters within the getServerSideProps() method? Below is the snippet of my code. The objective of my code is to extract parameters from the URL, fetch data from the API, and render it on the front end. import { useRouter } from ...

Tips on rearranging the location of a div element within a directive

I have created a custom directive that displays two divs, Div1 and Div2, with a splitter in the middle: Splitter Image Now, I am looking for a way to swap the positions of these two divs dynamically using an Angular directive. I thought about using ng-swi ...

Executing a POST request with AJAX in jQuery to communicate across different domains and fetching XML data as

Is it possible to send an AJAX request using the POST method and receive XML as a response text? If so, please provide me with the steps to achieve this. For example: url : "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate" data ...

Add several converted links as variables in each section

The title may not be the clearest, but I am facing a challenge with an ecommerce site that has unmodifiable HTML. My goal is to include additional links for each product displayed on a page showcasing multiple products. Each link should be unique to its re ...

Enabling communication between two single file components

Is there a way for two single file components to communicate with each other? Consider this scenario: I have two components, Content.vue and Aside.vue I want to be able to trigger an update in the Content.vue component when a button inside Aside.vue is c ...

Unexpected behavior observed in JavaScript and AJAX functionality

In my web development project, I've decided to incorporate JavaScript and AJAX for the signup form functionality. However, I seem to be facing some challenges as I try to post all the textbox values from the signup form through AJAX. The code snippe ...