简体   繁体   中英

Sorting graphQL data in JavaScript

Very much appreciated for reading this one, It might seem like easy for you, but I am quite new. so bear with me: I have a query in GraphQL which gives me the following results:

  "data": {
"completeglobaldata": [
      {
        "increasehotdays": 43,
        "countryname": "Afghanistan"
      },
      {
        "increasehotdays": 66.1,
        "countryname": "Angola"
      },
      {
        "increasehotdays": 0,
        "countryname": "Anguilla"
      },
      {
        "increasehotdays": 0,
        "countryname": "Åland Islands"
      },
      {
        "increasehotdays": 51.9,
        "countryname": "Albania"
      },
]
}

Yet, now I want to sort the data in a descending way with JavaScript sort. The problem is that GraphQL will return objects and I do not understand how this would work.. I have been stuck on the array/sort page for some good hours now.

export const sortDescendingHotDays = (completeglobaldata) => {
  const countryTemperatures = completeglobaldata.map((country) => ({
    ...completeglobaldata,
  }));

  return completeglobaldata.sort((a, b) =>
    a.country.increasehotdays < b.country.increasehotdays ? 1 : -1
  );
};


This is obviously wrong, but it shows how lost I am. Oh, I am using React by the way. Ofcourse I could easily change the graphQL query to:

query MyQuery {
  completeglobaldata(order_by: {increasehotdays: desc}) {
    increasehotdays
    countryname
  }
}

But this is not possible in my situation.I really need to get the data and then sort it using Javascript sort

Thank you for your help:)

Check out this documentation: filtering-pagination-and-sorting-GRAPHQL .
I hope it should helps you

You were close, There isn't a country key on your individual objects, and when you're using sort. you're already comparing two different country objects.

completeglobaldata.sort((a,b) => b.increasehotdays - a.increasehotdays)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM