1

Consider the following object as an example:

var object = {
  some_key: 'some value',
  some_other_key: 'some other value',
  AKey: 'notice that some will have underscores and some wont.'
  callBackl: 'http://google.ca'
}

Should become:

var object = {
  AKey: 'notice that some will have underscores and some wont.'
  callBackl: 'http://google.ca'
  some_key: 'some value',
  some_other_key: 'some other value',
}

I haven't found a lodash solution to this and a lot of solutions I do find on stack, such as this one, seem .... complicated. Maybe this isn't trivial?

Ideas?

Community
  • 1
  • 1
TheWebs
  • 12,470
  • 30
  • 107
  • 211
  • Duplicate of http://stackoverflow.com/q/5467129/7947361 – captncraig May 04 '17 at 22:51
  • @OliviaRuth The issue with this solution is that its messy. Its not clean. Its gross. – TheWebs May 04 '17 at 22:52
  • It is what it is. http://stackoverflow.com/a/31102605/7947361 seems to be the most up to date. That old, and with that many votes, it seems as good as you are going to get. – captncraig May 04 '17 at 22:53

1 Answers1

3

EDIT: it appears as though I was incorrect when I first posted, newly defined Javascript specs state that (to my utter surprise) javascript objects do indeed have ordering (Sort JavaScript object by key)! This being said, I still would not recommend attempting to order elements of an object itself, but rather to go with the key-sorting approach that I have described below. Object.keys(obj) as well as a few other edge cases appear to still have no guarantee of ordering and I would argue that that is good enough reason to stay away from depending on the order of the keys of your objects.


Original post below.

Unless I understand javascript incorrectly, the keys in a javascript object have no guaranteed ordering. This means that, in theory, I could create the object

{'a':'hi', 'c':'hey', 'b':'hello'}

And, on iterating through its keys I could get any possible ordering of 'a', 'b', and 'c'.

If you need to display your objects in any particular order, I would suggest accessing the keys of your object and sorting those and then accessing your object in the sorted order of your newly sorted keys. (Can be seen implemented here: Is there a way to sort/order keys in JavaScript objects?)

Community
  • 1
  • 1
John Gallagher
  • 525
  • 4
  • 15