What is the most efficient method for sorting a complex JSON object?

I have a JSON object with multiple nested levels:

{
"myJson": {
  "firstGroup": {
"0": [
                {
                    "month": 1.0,
                    "amount": 1.7791170955479318,
                    "name": "dummy1",
                    "nr": 3
                },
                {
                    "month": 2.0,
                    "amount": 324.0,
                    "name": "dummy2",
                    "nr": 1
                },
                {
                    "month": 3.0,
                    "amount": 32323.0,
                    "name": "dummy3",
                    "nr": 2
                }
],
"yearlyResults": {
"0": [
{
                    "month": 1.0,
                    "amount": 100000,
                    "name": "dummy1",
                    "nr": 3
                },
                {
                    "month": 2.0,
                    "amount": 3000000,
                    "name": "dummy2",
                    "nr": 1
                },
                {
                    "month": 3.0,
                    "amount": 60000,
                    "name": "dummy3",
                    "nr": 2
                }
]
}           
 },
 "secondGroup": {
// Structured similarly to firstGroup 
 }
},
"success": true
}

My goal is to sort the data within the "0" and "yearlyResults" groups in ascending order within this JSON....

Here's the code I'm using:

/**
   * Function for sorting data in ascending order
   * @param property any
   */
  sortByProperty(property) {
    return (a, b) => {
      if (a[property] > b[property]) {
        return 1;
      }
      else if (a[property] < b[property]) {
        return -1;
      }
      return 0;
    };
  }
 /**
   * Display sorted data using this function
   */
private getSortedData() {
this.myService.getData().subscribe();
(resp: any) => {
const data = resp.success ? resp.myJson : null;
        // Sorting for firstGroup
        const firstData = data['firstGroup'];
        const currentFirstData = firstData['0'];
        const currentFirstYearly = firstData.yearlyResults['0'];

         // Sorting for secondGroup
        const secondData = data['secondGroup'];
        const currentSecondData = secondData['0'];
        const currentSecondYearly = secondData.yearlyResults['0'];

  if (null !== data && data) {
 currentFirstData.sort(this.sortByProperty('nr'));
 currentFirstYearly.sort(this.sortByProperty('nr'));
 currentcurrentSecondData.sort(this.sortByProperty('nr'));
 currentSecondYearly.sort(this.sortByProperty('nr'));
...
}
}
}

While my solution works, it may not be efficient enough! Sorting two groups is manageable, but with 20 or 30 groups, it becomes more challenging. Is there a way to iterate through and sort the JSON groups? Any assistance would be greatly appreciated!

Answer №1

Utilize the Object.entries method to loop through all key-value pairs and then apply Array.prototype.reduce to construct the new object. Here's an example:

const data = JSON.parse('{ "myJson": { "firstGroup": { "0": [ { "month": 1.0, "amount": 1.7791170955479318, "name": "dummy1", "nr": 3 }, { "month": 2.0, "amount": 324.0, "name": "dummy2", "nr": 1 }, { "month": 3.0, "amount": 32323.0, "name": "dummy3", "nr": 2 } ], "yearlyResults": { "0": [ { "month": 1.0, "amount": 100000, "name": "dummy1", "nr": 3 }, { "month": 2.0, "amount": 3000000, "name": "dummy2", "nr": 1 }, { "month": 3.0, "amount": 60000, "name": "dummy3", "nr": 2 } ] } } }, "success": true }');

const object = data.myJson;

const sortSubGroupByProperty = (subGroup, property) => {
  return subGroup.sort((a, b) => {
    if (a[property] > b[property]) {
      return 1;
    }
    else if (a[property] < b[property]) {
      return -1;
    }
    return 0;
  });
}

const result = Object.entries(object).reduce((result, entry) => {
  const [groupName, group] = entry;
  result[groupName] = {
    ...group,
    0: sortSubGroupByProperty(group[0], 'nr'),
    yearlyResults: {
        ...group.yearlyResults,
        0: sortSubGroupByProperty(group.yearlyResults[0], 'nr')
    }
  };
  return result;
}, {});

console.log(result);

Answer №2

In this code snippet, everything is running smoothly without any errors. The issue arises when working in the IDE and implementing the following code:

this.kpisService.getAllKpisMonthData(yearString).subscribe(
  (resp: any) => {
    const data = resp.success ? resp.kpi : null;

    // console.table(data);

    if (null !== data && data) {
      const sortSubGroupByProperty = (subGroup, property) => {
        return subGroup.sort((a, b) => {
          if (a[property] > b[property]) {
            return 1;
          }
          else if (a[property] < b[property]) {
            return -1;
          }
          return 0;
        });
      };

      const result = Object.entries(data).reduce((result, entry) => {
        const [groupName, group] = entry;
        result[groupName] = {
          ...group, // This is where the issue lies
          0: sortSubGroupByProperty(group[0], 'nr'),
          yearlyResults: {
            ...group.yearlyResults,
            0: sortSubGroupByProperty(group.yearlyResults[0], 'nr')
          }
        };
        return result;
      }, {});

      console.log(result);

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

Is Angular 2+ responsible for loading the entire module or only the exported components within it?

I'm dealing with a situation where I have a large module but only need to export one specific component. I'm wondering if Angular loads the entire module or just the exported components, as I want to optimize performance without compromising the ...

Creating a universal wrapper function to serve as a logging tool?

Currently, I am working on a generic JS function that can wrap any other function. The purpose of this wrapper is to execute the wrapped function, log the input and output events, and then return the output for "transparent" logging. However, as I attempt ...

What is the most effective way to transmit multiple pieces of server-side data to JavaScript?

Imagine having multiple Javascript codes embedded in pages. Currently, it's simple to initialize variables by using Print/Echo statements to set JavaScript values. For example: var x = <?php echo('This is a value');?> Initially, I co ...

Using Powershell to work with JSON objects and NoteProperty attributes

Currently, I am exploring the possibility of utilizing Zabbix API in conjunction with PowerShell to automate various monitoring tasks. My goal is to fetch "items" based on specific parameters passed to my function. For instance, if the -itemDescription par ...

Attempting to keep a:active state active until another link is clicked

My goal is to have two links, "hot" and "update." When "hot" is clicked, it should turn red and "update" should turn black. Conversely, when "update" is clicked, it should turn red and "hot" should turn black. This functionality works perfectly on a Fiddl ...

Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array: var Bluebird = Promise.noConflict(); var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ...

Jest came across a token from nestjs that it did not expect

I've hit a roadblock with running my end-to-end tests in Nest.js using Jest. Every time I attempt to execute my e2e test, an error keeps popping up Jest encountered an unexpected token Even though all other test suites ran smoothly, this particular ...

Looking for a way to implement a column search filter in JqGrid using server-side code?

I have a JqGrid table where I am passing Json data through my controller. The paging, sorting, and filter/search functionality are all handled by the controller. I specifically want the filter search to be dynamic and not trigger on enter, so searchOnEnter ...

Rearrange the position of the customized google map marker to appear just above the latitude

Can you provide guidance on how to move a customized Google Map marker above a specific latitude and longitude point? You can view the code structure in this JSBIN: Link. I have used three object arrays for reference. Where should I insert the "anchor" i ...

The performance of web API calls on an Angular 7 app deteriorates gradually with each subsequent call

My Angular application in C# is experiencing a slowdown when making calls to the web API and executing a stored procedure. While the C# code performs quickly, the 'Content Download' process is progressively slowing down with each call. https://i ...

Retrieving the height of the HTML body once all data has finished loading in AngularJS

Trying to determine the height of the HTML document (body) after loading content from a service using AngularJS. /* DISPLAY RECENT POSTS */ app.controller('RecentPostsController', function ($scope, $http) { $http.get("/site/recentpostsjs ...

Challenges in Implementing Shadows with Animations in ThreeJS MeshDepthMaterial

I'm facing an issue where casting shadows through transparent parts of my Mesh using the MeshDepthMaterial causes the shadows of animated objects to stop moving along with the animation. You can see an example of this problem here: https://jsfiddle.n ...

Tips for hiding a div element until its visibility is toggled:- Set the display property of

Looking for some guidance on this jQuery code I'm working with to create a toggle menu. The goal is to have the menu hidden when the page loads, and then revealed when a button is clicked. However, currently the menu starts off being visible instead o ...

Is there a way to simulate the parameters injected into an fs callback without actually interacting with the filesystem during testing?

I'm currently utilizing Chai, Mocha, and Sinon for my testing framework. At the moment, I have a functioning test, but I find myself having to set up a directory and populate it with files just to make my tests run successfully. This approach doesn&a ...

Disabling 'Input Number' feature is ineffective in Firefox browser

Is there a way to prevent the input value from changing when the up or down arrow is held, even if the input is disabled? I want to retain the arrows without allowing this behavior on Firefox. Give it a try: Press the up arrow. After 5 seconds, the input ...

Cross browser array filtering in javascript

I'm facing a challenge that I haven't been able to find a solution to yet. I have an array, let's say var oldArr=['one','two','3'];, and I need to create a new array containing only the string values. Currently, ...

Organizing a set of columns under a fresh header in the JSON serialization process

My dataset in Pandas consists of the following details: start end compDepth compReleaseDepth compMeanRate 0 0.0 0.62 58.0999985 1.5 110 1 0.66 1.34 57.1399994 3 94 2 ...

A program designed to access and retrieve a universal variable

It seems like a simple task, but I can't seem to figure it out. I'm trying to assign the currentUserId within the getCurrentUser function so that I can use it in other functions. Currently, the code below is returning undefined. What am I overl ...

Showcasing the information of a selected row and retrieving data from a database within the same jsp page using ajax technology

I am a beginner in Java and JSP. I have a JSP page that fetches data from a database and displays it in a table. I want to be able to display the details of each row when the user clicks on the row in the same JSP page. Can anyone help me with this? Below ...

Leveraging parameters or pre-established variables within CSS

After successfully adding CSS to customize a checkbox, I utilized a local file (check.png) as the background image and cropped it within the checkbox boundaries. Below are two examples of checkboxes: one checked and one unchecked I am now curious if ther ...