Home > Net >  How to order an object by a parameter?
How to order an object by a parameter?

Time:09-17

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.

CodePudding user response:

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]));
  • Related