Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort a nested query result

I have the following output:

    {
      "data": {
        "title": "Movie 4",
        "data": [
          {
            "userId": 2,
            "profile": { "profileImage": "image" },
            "round": 1,
          },
         {
            "userId": 4,
            "profile": { "profileImage": "image" },
            "round":6,
          },
          {
            "userId": 10,
            "profile": { "profileImage": "image" },
            "round": 4,
          },
        ]
      }
    }

The output im expecting is the following:

{
  "data": {
    "title": "Movie 4",
    "data": [
      {
        "userId": 2,
        "profile": { "profileImage": "image" },
        "round": 1,
      },
      {
        "userId": 10,
        "profile": { "profileImage": "image" },
        "round": 4,
      },
     {
        "userId": 4,
        "profile": { "profileImage": "image" },
        "round":6,
      },
    ]
  }
}

I want to sort my output by my nested value round.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is where im collecting all the data, but i dont know how to sort it:

let combinedResult = { 
  title: combinations["data"]["title"],
  data: galleryData.map((item, i) => {
     let combination = combinations["data"]["eventdata"].find(c => c.partner === item.userId);
    return { ...item, round: combination.round, roundStart: combination.roundStart, roundEnd: combination.roundEnd} 
  })
};

I already tried to sort before the return with this but it didnt work:

const sorted = Object.entries(resultAfter)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB));

>Solution :

Another option is to use sort() method

let json = {
      "data": {
        "title": "Movie 4",
        "data": [
          {
            "userId": 2,
            "profile": { "profileImage": "image" },
            "round": 1,
          },
         {
            "userId": 4,
            "profile": { "profileImage": "image" },
            "round":6,
          },
          {
            "userId": 10,
            "profile": { "profileImage": "image" },
            "round": 4,
          },
        ]
      }
    }
    
let arr = json.data.data
arr.sort((a,b) => a.round - b.round)
json.data.data=arr
console.log(json)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading