0

I have a ruby (sequel) generating hash with

equipment = Equipment.select(:id, :gl_code, description).order(:description).to_hash(:id) 

and I get a properly ordered hash. I also verified that order stays the same when hash is converted to json. However, in ajax receiving json

console.log(res.body.equipment); 

shows reordered hash by numeric id key which I don't want because in drop down list I want to show items ordered by description just like ruby sends it.

How to make javascript keep the same order as it gets sent by the server?

Shreko
  • 321
  • 4
  • 16
  • 3
    This is what the standards requires. If you want another order, use an array. – Denys Séguret May 26 '15 at 15:40
  • @minitech False. ES6 now specifies an order that was already used. See http://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties – Denys Séguret May 26 '15 at 15:42
  • @DenysSéguret: JSON is not JavaScript. As far as I’m aware, JSON is still http://json.org/, which states that “an object is an unordered set of name/value pairs.” – Ry- May 26 '15 at 15:43
  • @minitech Well. That's true for the JSON specification but when the object is built in a JS engine from the JSON string (as in this question), the ordering of the keys is the one of the JS specification. – Denys Séguret May 26 '15 at 15:46
  • @DenysSéguret: Oh, I edited my comment to suggest using an array (which was the point of saying JSON objects were unordered) but deleted it because that the same as yours. – Ry- May 26 '15 at 15:49
  • This being said, you raise an hypothetical but valid point. Not having any specification imposing a conservation of the keys order in JSON might be worrying if we consider intermediate transformations (compressions for example). – Denys Séguret May 26 '15 at 15:52
  • I could use an array for building dropdown, reason for hash was to be able to display relation between workstation and equipment using {{equipment[equipment_id].description}} as I loop through list of workstations. Or I can do join query in DB. Thanks for your help. – Shreko May 26 '15 at 16:23

0 Answers0