Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object keys in different order after running Object.keys [duplicate]

I ran into the oddest behavior while working on a ticket this morning. If you see below after running Object.keys, the order of the keys has changed leaving P after F.

I tried the following:

  • Object.entries - got the same result as Object.keys
  • For loop - got the same result as Object.keys
  • I thought perhaps that the # was throwing off the sorting, so I removed it and re ran the test. - got the same result as Object.keys

I looked at the ECMAScript spec and this should not be case. Any ideas what could be causing this behavior ?

enter image description here

P.S I fixed the issue by running .sort() on the array but was curious to know what's causing the keys to go out of order.


1 Answers

So you are trying to turn a Map (unordered) into an Array (ordered). Some browsers dump the keys based on the order they are added to the object. Some do it other ways. Since it is browser dependent the best you can aim for is sorting said list.

I would suggest that after you dump it to an array, you should .sort() it how you see fit. It accepts a function you would need. Granted, it is case specific, so you would need to likely leverage the optional passed in function for sort to compare it in the way which best works for your use case. Since sort's inputs can be as complex as you like, you could also use it to sort on the contents of said values instead of just the keys.

like image 170
Fallenreaper Avatar answered Dec 24 '25 05:12

Fallenreaper