0

I have the following object composed of the following:

[enter image description here][1]

What you see on the screen (the object), is the following: dataUserProfile.permissions[dataOriginSelect].permissions

It turns out that I want to order the object according to the 'order' parameter, from smallest to largest.

I am using something like:

const sortByFieldInt = (listToSort,field) => {
  return listToSort.sort((a, b) => {
    if(a[field] < b[field]) {
      return -1;
    }
    if(b[field] < a[field]) {
      return 1;
    }
    return 0;
  });
}

which I use like this: sortByFieldInt([dataUserProfile.permissions[dataOriginSelect].permissions], 'order')

but it fails me, what am I doing wrong? I really appreciate your time to read me and help.

1 Answers1

0

Try Object.keys() with Array.prototype.map() to transform your object into array.

const object = dataUserProfile.permissions[dataOriginSelect].permissions; // Your object in this case
console.log(Object.keys(object).map((key) => object[key]));
Huy Pham
  • 400
  • 4
  • 14
  • Yes, it worked for me, I added my sort function to it and it works fine: `console.log(sortByFieldInt(Object.keys(dataUserProfile.permissions[dataOriginSelect].permissions).map((key) => dataUserProfile.permissions[dataOriginSelect].permissions[key]), 'order'));` – Francisco.js Sep 16 '22 at 18:00
  • How can I iterate the array of objects that I stay ordered? Attached image at the end of the post – Francisco.js Sep 16 '22 at 18:32
  • I tried with .map() after sorting but I think 'Object.keys' doesn't accept – Francisco.js Sep 16 '22 at 18:33
  • There are many ways to iterate an array. Check this thread [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript). – Huy Pham Sep 16 '22 at 18:41