Home > Blockchain >  sort objects by key value 0 by number size
sort objects by key value 0 by number size

Time:05-07

how i can sort this object by user_id ?

{
 key_1: { user_id: 3 },
 key_2: { user_id: 1 },
 key_3: { user_id: 2 }
}

I need this:

{
 key_2: { user_id: 1 },
 key_3: { user_id: 2 },
 key_1: { user_id: 3 }
}

thanks for help

CodePudding user response:

ES6 states a traversal order for object keys (see this article):

  • Integer indices in ascending numeric order.
  • Then, all other string keys, in the order in which they were added to the object.
  • Lastly, all symbol keys, in the order in which they were added to the object.

This means that as long as you're using non integer keys of strings or symbols (not both), you can "sort" an object keys by creating a new object with the keys in the insertion order you need.

For example, use Object.entries() to get an array of [key, value] pairs, sort by user_id, and then convert back to an object using Object.fromEntries():

const obj = { key_1: { user_id: 3 }, key_2: { user_id: 1 }, key_3: { user_id: 2 }}

const result = Object.fromEntries(
  Object.entries(obj)
    .sort(([, a], [, b]) => a.user_id - b.user_id)
)
  
console.log(result)

However, this would fail for an object with integer keys:

const obj = { 1: { user_id: 3 }, 2: { user_id: 1 }, 3: { user_id: 2 }}

const result = Object.fromEntries(
  Object.entries(obj)
    .sort(([, a], [, b]) => a.user_id - b.user_id)
)
  
console.log(result)

So, it's better and less error prone to create an array of keys, sort it by the order you want, and then use it to get property values in that order:

const obj = { key_1: { user_id: 3 }, key_2: { user_id: 1 }, key_3: { user_id: 2 }}

const result = Object.keys(obj)
  .sort((a, b) => obj[a].user_id - obj[b].user_id)
  
console.log(result.forEach(key => console.log(obj[key])))

CodePudding user response:

You can't. I think you are missing the nature of objects and arrays. The order of properties in an object doesn't matter. Of course, in an array it may.

If, for example, you receive an object and you want to display that data sorted, I would recommend you transform that object into an array and then sort it:

const object = {
  key_1: {
    user_id: 3
  },
  key_2: {
    user_id: 1
  },
  key_3: {
    user_id: 2
  }
};
const array = Object.entries(object)
const sortedArray = array.sort(([, aValue], [, bValue]) => aValue.user_id > bValue.user_id)

console.log(sortedArray)

  • Related