0

I have been trying for hours to sort a multidimensional object using an "orderKey" field. Unfortunately, I have not been able to sort it with the numerous examples I've found on the internet.

My Object (simplified):

{
"entry1": {
    "id"          : 1,
    "title"       : "Title",
    "shortDesc"   : "description",
    "price"       : 5,
    "isOnline"    : true,
    "orderKey"    : 2,
},
"entry2": {
 "id"             : 1,
    "title"       : "Title",
    "shortDesc"   : "description",
    "price"       : 10,
    "isOnline"    : true,
    "orderKey"    : 7,
},
...

I want to be able to sort the object by "orderKey" (asc/desc).

I would be very grateful for some help.

Edit: I have found the linked post as well, but I am not able to make it work for my example.

Bolin
  • 119
  • 10

1 Answers1

1
// define sort functions for ascending or descending
const sortAscending = (a, b) => a[1].orderKey < b[1].orderKey ? -1 : 1
const sortDescending = (a, b) => a[1].orderKey > b[1].orderKey ? -1 : 1

// define function to sort the object that accepts an object and a toggle for ascending or descending order
const sortObject = (obj, ascending = true) => {
    // convert the object into an array of key value pairs
    return Object.entries(obj)
        // sort the array in the direction specified by the toggle
        .sort(ascending ? sortAscending : sortDescending)
        // use reduce to convert the array of key values back to an object
        .reduce((memo, [key, value]) => ({ ...memo, [key]: value }), {})
}

// call the object sorting function with data
sortObject({
    "entry1": {
        "id"          : 1,
        "title"       : "Title",
        "shortDesc"   : "description",
        "price"       : 5,
        "isOnline"    : true,
        "orderKey"    : 2
    },
    "entry2": {
        "id"          : 1,
        "title"       : "Title",
        "shortDesc"   : "description",
        "price"       : 10,
        "isOnline"    : true,
        "orderKey"    : 7
    }
}, false) // use true for ascending
Billy Moon
  • 57,113
  • 24
  • 136
  • 237