`Is there a way to sort a deeply nested object by its values?`

I need assistance sorting an array of hospitals based on the lowest value of the amountinINR key, especially when dealing with deeply nested arrays of hospital objects. Does anyone know how to achieve this without using third-party libraries like lodash or underscore?

Below is a snippet of my JSON object:

// My first attempt 

 for (let i = 0; i < result.length; i++) {
                    for (let j = 0; j < result[i].procedure.length; j++) {
                        for (let k = 0; k < result[i].procedure[j].hospital.length; k++) {
                            if (k === 0 || k === 1 || k === 2) {
                                result[i].procedure[j].hospital[k].amountinDoller = `<b> ${hospitalDol.amountinDoller || 'N/A'} </b>`;
                                result[i].procedure[j].hospital[k].amountinINR = `<b>${hospitalInr[k].amountinINR || 'N/A'} </b>`
                            }
                        }

                    }
                }

---------------------------------------------------------------------------------------
//  here i am using map() native method of javascript 
     ** my Second Attempt** 
     result.map((category,index) => {
         return category.procedure.map((procedures,index) => {
           return procedures.hospital.sort((a,b) => { return a.amountinINR - b.amountinINR});
     })
    });


// JSON Object 
    let result =  [{
                "_id": "58711a64546a7b5bf2d07b4d",
                "procedure": [...] // Truncated for brevity
                "category": [{
                    "_id": "58711a64546a7b5bf2d07b4d",
                    "name": "Cancer Surgeries",
                    "status": true,
                    "createdAt": "2017-01-07T16:42:12.696Z",
                    "__v": 0
                }]
            }]

I'm looking for a way to sort hospitals by the lowest amountinINR value and return the same JSON object with the sorted hospitals. Any optimized code suggestions would be greatly appreciated.

Answer №1

One way to organize the arrays within result is by using Array#sort and iterating through them with Array#forEach. This is particularly useful when your map function does not return any values.

result.forEach(r => r.procedure.forEach(p => p.hospital.sort((a, b) => a.amountinINR - b.amountinINR)));

Answer №2

Essentially providing a similar response to Nina Scholz, albeit utilizing an older technique.

var results = [{
  "_id": "58711a64546a7b5bf2d07b4d",
  "procedure": [{
    "_id": "58711aa8546a7b5bf2d07b4e",
    "hospital": [ // Hospital data here ],
    "procedures": {
      "_id": "58711aa8546a7b5bf2d07b4e",
      "name": "Breast Conservative surgery",
      "categoryId": "58711a64546a7b5bf2d07b4d",
      "status": true,
      "createdAt": "2017-01-07T16:43:20.888Z",
      "__v": 0
    }
  }, { 
    "_id": "58711b8d546a7b5bf2d07b52",
    "hospital": [ // Hospital data here ],
    "procedures": {
      "_id": "58711b8d546a7b5bf2d07b52",
      "name": "Hysterectomy + Laparotomy",
      "categoryId": "58711a64546a7b5bf2d07b4d",
      "status": true,
      "createdAt": "2017-01-07T16:47:09.982Z",
      "__v": 0
    }
  }, { 
     // More procedure data here 
  }],
  "category": [{
    "_id": "58711a64546a7b5bf2d07b4d",
    "name": "Cancer Surgeries",
    "status": true,
    "createdAt": "2017-01-07T16:42:12.696Z",
    "__v": 0
  }]
}];
//Loop through results and sort hospital data based on amountinINR
for (var resultIndex = 0; resultIndex < results.length; resultIndex++) {
  var result = results[resultIndex];
  for (var procedureIndex = 0; procedureIndex < result.procedure.length; procedureIndex++) {
    var procedure = result.procedure[procedureIndex];
    //foreach result, modify "procedure"
    procedure.hospital = procedure.hospital.sort(function(a, b) {
      return a.amountinINR - b.amountinINR;
    });
  }
}
//Log sorted results
console.log(results);

Answer №3

I have already provided an answer, but someone else might find it useful as a concise statement. - @Nina Scholz

let result = [{
  "_id": "58711a64546a7b5bf2d07b4d",
  "procedure": [{
    "_id": "58711aa8546a7b5bf2d07b4e",
    "hospital": [...
// The code continues.
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

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

Loop through items in Node.js

Is anyone familiar with a way to obtain the computed styles of anchor tags when hovering over them on a webpage? I've tried using this function, but it only returns the original styles of the anchor and not the hover styles. Any assistance would be gr ...

Fresh React framework

I haven't worked on a React app in a while, but when I decided to start a new one and import my old function, I encountered the following error: C:/Users/Hello/Documents/Dev/contacts/client/src/App.tsx TypeScript error in C:/Users/Hello/Documents/Dev ...

Create a new object in Three.js every x seconds and continuously move each object forward in the Z-axis direction

I am currently developing a Three.js endless runner game where the player controls a character dodging cars on a moving road. At this early stage of development, my main challenge is to make the hero character appear to be moving forward while creating the ...

Tips for adjusting the text color of input fields while scrolling down

I am currently working on my website which features a search box at the top of every page in white color. I am interested in changing the color of the search box to match the background color of each individual page. Each page has its own unique background ...

Error in Node.js: Unhandled promise rejection due to undefined value

We're currently facing an issue with the create user controller in Node.js Express. The problem arises when attempting to sign up on the front end, resulting in an error message: "Unhandled promise rejection error value is not defined." Although it ap ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Is it possible to utilize a string as an object in PHP?

Imagine having this JSON object: $object = { "recipe": { "apples": 5, "flour": "2 lbs", "milk": "2 cartons" } } Now, look at this function: private function fetch_quantity($ingredient) { $json_data = json_decode($object); return $js ...

What is the best way to extract data from the JSON output of a gerrit query?

I'm facing a situation where I need to retrieve specific data from the output of a gerrit query, but unfortunately, I'm having difficulty using awk. Here is the command I am running: ssh -p 29418 gerrit.abc.se gerrit query --format=JSON project ...

Updating an Object in vue.js Upon Click Event to Add a New Value

I currently have a code snippet that looks like the following: arr = [ { val1: a, val2: b }, { val1: a, val2: b }, { val1: a, val2: b } ] <div v-for="single in arr"> <button v-on:click="addSome"></button> </div> When I c ...

Encountering difficulties accessing XML file on server via anchor tag

I have an XML file on the server that I am attempting to open in a browser when the user clicks on a link. Below is how I have set up the link, but it is not opening the file: Code: <a title="View XML" href="file://///90.0.0.15/docmgmtandpub/PublishD ...

Tips for clearing out outdated information from a bar chart

My bar chart is receiving JSON data based on the selected dropdown value. The chart updates when the dropdown changes, but there seems to be a problem with the hover functionality causing the last visited value to shake the chart. Any suggestions on how ...

JSON serialization allows you to efficiently store and exchange various objects of different types

I have two derived classes that inherit from an abstract base class public class Class1 : MainBaseClass { public int attribute1 {get; set;} public int attribute2 {get; set;} } public class Class2 : MainBaseClass { public int attributex {get; set ...

Maintain MUI Autocomplete in the open state even after making a selection from the

Whenever I select certain options on my Autocomplete component, I want to keep the component open. However, each time I click on onChange, the Autocomplete closes automatically and I can't seem to find a way to prevent this. Is there a workaround? In ...

Angular JS - Establishing a Connection to Woocommerce OAuth v1

I'm having trouble authenticating myself with the rest service. I attempted to use this library to generate all the necessary parameters as mentioned here, and I constructed the request like this: $scope.oauth = new OAuth({ consumer: { p ...

How can I display the output from Geocoder in a text box using the ArcGIS JavaScript API?

I am trying to customize the Geocoder text box in the ArcGIS JavaScript API by overriding the default search result. Although I have written some code for this purpose, I am not satisfied with the results. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...

Receiving an empty string from Chrome FileReader when dealing with large files (300MB or more)

Objective: The task is to read a file from the user's file system as a base64 string in the browser The size of these files can be up to 1.5GB Challenge: A script that works flawlessly on Firefox, regardless of the file size On Chrome, the script p ...

Which is the better choice for me - webpack or create-react-app?

What's the best way to kickstart my react app - webpack or create-react-app? Are there any benefits to using webpack instead of create-react-app? ...

Customizing JSON response with Spring MVC

I'm facing a challenge with my RestController method that returns data in a custom JSON format. Originally, I was using a HashMap to build the response: // The method which builds custom JSON response from retrieved data public List<HashMap<Str ...

The HTTP request is being executed twice for some reason unknown to me

import React, {useState, useEffect} from 'react' export function UseStateExample() { // This is a named export that must be used consistently with {} when importing/exporting. const [resourceType, setResourceType] = useState(null) useEffect ...