What is the best way to arrange the information in JSON in ascending order and display it in a table format?

I am working with a mat-table and have used GET to display my data. I now want to sort the data in ascending order based on the db-nr from my JSON.

Here is an excerpt from my JSON:

{
                    "period": 12.0,
                    "amount": 0.0,
                    "name": "Test1",
                    "mandantKagId": 0.0,
                    "db-nr": 5
                },
                {
                    "period": 12.0,
                    "amount": 0.0,
                    "name": "Test2",
                    "mandantKagId": 0.0,
                    "db-nr": 2
                },
                {
                    "period": 12.0,
                    "amount": 0.0,
                    "name": "Test3",
                    "mandantKagId": 0.0,
                    "db-nr": 4
                }

// Typescript code

// Populating the table with data
  private loadData() {
this.planBwaService.getAllPlanBwaData(yearString).subscribe(
          (resp: any) => {
            const planBwa = resp.success ? resp.bwaResult.planBwa : null;
            const data = planBwa['0'];
            const allYearlyResults = planBwa.yearlyResults;
            const yearlyResults = allYearlyResults['0'];
            if (null !== data && data && yearlyResults && yearlyResults !== null) {
              this.isLoading = false;
              const rows = [];
              const planBwaData: string[] = [];
              const names = _.uniq(data.map((d) => d.name)) as string[];
              for (const n of names) {
                planBwaData[n] = data.filter((d) => d.name === n);
                if (planBwaData[n].length > 0) {
                  const row: any = { name: planBwaData[n][0].name, values: {}, note: '', mandantKagId: planBwaData[n][0].mandantKagId };
                  for (const item of planBwaData[n]) {
                    row[item.period] = this.transformAmount(item.amount);
                  }
                  const yrNameItem = yearlyResults.find((yr) => yr.name === n);
                  row.values.currentYear = (yrNameItem && yrNameItem !== null) ? this.transformAmount(yrNameItem.amount) : null;
                  rows.push(row);
                }
              }
              this.dataSource = new MatTableDataSource<PlanBwa>(rows);
              this.dataSource.data = rows;
            } 
        );
}

Could you please provide some guidance on how I can proceed with this implementation?

Answer №1

It appears that your json extract may be a bit confusing. Is it structured as an array of objects? If so, you can easily organize the data using

yourdata.sort((a, b) => a['db-nr'] - b['db-nr'])

Here is an example:

const data = [{
  "period": 12.0,
  "amount": 0.0,
  "name": "Test1",
  "mandantKagId": 0.0,
  "db-nr": 5
}, {
  "period": 12.0,
  "amount": 0.0,
  "name": "Test1",
  "mandantKagId": 0.0,
  "db-nr": 2
}, {
  "period": 12.0,
  "amount": 0.0,
  "name": "Test1",
  "mandantKagId": 0.0,
  "db-nr": 4
}]

data.sort((a, b) => a['db-nr'] - b['db-nr'])

console.log(data)

Edit: To convert your JSON into a JavaScript object, you can utilize JSON.parse

Answer №2

  1. To arrange in decreasing order:

    const elements = items.sort(function (x, y) { return y.db-nr - x.db-nr; });

  2. To sort in ascending order:

    const elements = items.sort(function (x, y) { return x.db-nr - y.db-nr; });

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 are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...

Learning how to interpret input from the command line in Vertx

Would appreciate some guidance on how to read command line arguments in vert.x using JavaScript. For instance, I am wondering how to go about reading: arguments(arg1, arg2, arg3) vertx run example.js arg1 arg2 arg3 ...

Adjust the HTML content prior to displaying it to prevent any flickering

Is there a way to run code before the page is rendered, such as updating dates or converting text to HTML, without causing flickering when reloading multiple times? How can I ensure the code runs as it's drawn instead of waiting until the end to redra ...

What is the best way to break down my node module into separate files?

I am currently in the process of organizing my node module functions by splitting them into separate files to accommodate numerous functions that need to be added. My objective is to call the main file's functions from files located within the lib di ...

Angular UI directive for modal confirmation

Looking to create a custom Angular directive using angular-bootstrap that mimics the confirm() function. Check out the visual result and desired behavior in this plunk: http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview Now, I want to implement a directi ...

Encountering a TypeError when using the react useRef() hook

During my work on an app utilizing the webRTC API and working with the useRef() hook in React, I encountered an error Error: TypeError: myVideo.current is undefined ContextProvider SocketContext.js:27 promise callback*ContextProvider/< SocketCon ...

How to deal with an empty $_FILES array when there is file data present in $_POST

After reviewing multiple solutions, I noticed that they all utilize jQuery's .ajax() method. However, I have developed a more concise vanilla JS approach which has been quite successful for me. function ajax(options){ var settings = { met ...

When you hover over them, Material UI icons shrink in size due to the Border

I've been working on a React application that includes Material UI icons in the header. My goal is to add a border at the bottom of each icon when hovered over, but currently, the borders are too close to the icons. Another problem I'm facing is ...

The only information returned from calling mongoose's Model.save() method are the fields { _id, __

I've encountered a problem even though I believe I'm following all the right steps. I'm attempting to save an item from a form into my mongodb collection using mongoose. This is what my schema looks like: // stationmodel.js export const Sta ...

"Trouble with Express.js: CSS isn't loading, yet HTML displays

Click here to view folders and files server.js is the code I have created so far //importing packages const express = require('express'); const admin = require('firebase-admin'); const bcrypt = require('bcrypt'); const path = ...

Matter of Representing Nested For Loops in Javascript Arrays

When I have two arrays that intersect at certain elements, the resulting function should ideally output A, B, Y. However, in this case, it displays all possible combinations of lista.length * listb.length. <script> window.onload = function(){ ...

How to disable click event binding in Angular2 after it has been clicked once

Within my application, there is a button that has a click event attached to it: <button class="btn btn-default" (click)="doSomething()"> I am wondering if there is a way to remove the (click) event from the button within the doSomething method so t ...

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

What steps can be taken to activate a class upon a click event?

I have successfully implemented a hover function to change the background color on my element, but now I need to add an additional functionality to make the class active on click event as well. I have been struggling to find a solution for this issue and ...

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

Is there any distinction between using glob wildcards in the tsconfig.json file when specifying "include" as "src" versus "include" as "src/**/*"?

Is there a distinction between these two entries in the tsconfig.json file? "include": ["src"] "include": ["src/**/*"] Most examples I've come across use the second version, but upon reviewing my repository, ...

What is causing the backslash character to be removed from my ajax request?

When using Ajax to call a rest endpoint, the request takes two parameters: user and permission. $.ajax({ type: 'GET', cache: false, url: "/app/Rest/4.0/UserManagement/AddPermissionToUser", data: { username: encodeURI(user ...

Pass a link by pressing Enter

Although the title may seem odd, I'll explain what I'm attempting to accomplish. I have a login form with two input fields, a checkbox, and a submit button. You can view a screenshot of it here: https://i.sstatic.net/nE1FY.png The terms of use a ...

When an input element is being controlled from outside the modal using a portal, it is losing focus after a key press

[Resolved] The input component is experiencing a focus issue when any key is pressed, only when its value is controlled from outside of the portal. NOTE: I apologize for any confusion. While writing this post, I identified the problem in my code, but dec ...

"Implementing React to dynamically load and update value in component, enabling user interaction with the

As a newcomer to the world of React (16.4.2), I am trying to grasp its functionality without delving into Redux just yet; my focus is solely on understanding the core React library. In my application, there is an input component called RangeInput, which r ...