0

I'm trying to sort an object from db

MyOjbect : {
 key: {
val1:"value",
val2:"",
val3:time,
val4:...
...}
}

and I sorted the object by val3

const sorted = Object.entries(MyObject)
.sort((x,y) => {x[1].val3 - y[1].val3} );

and got an array type.

0:(2) ["key" , {val1:...val2:...}]

1:(2) ["key" , {val1:...val2:...}]

...

I tried reduce() to make it back to the object type, but it changes to be in unsorted order

enter image description here

How can I keep the order sorted and change the type to the object?

1547kime
  • 21
  • 4
  • Keys that represent non-negative integers will automatically fall into ascending order and will be put before any other keys. In general, it's not a good idea to rely on the order of items in an object and this is one of the reasons. If you want something ordered and serialisible, use an array. If you don't need it serialisable, then you can use a Map which always maintains insertion order. – VLAZ Jul 26 '21 at 07:46

1 Answers1

1

You can't. An object doesn't keep the sort order as an Array does it. If you want to have the keys sorted you need to use an Array.

Tarik Huber
  • 7,061
  • 2
  • 12
  • 18
  • [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/q/30076219) – VLAZ Jul 26 '21 at 07:41