1

I've been doing some reading and may have missed the obvious but don't think I have.

I have the following code:

var res = JSON.parse('{"products":{"0":"Please Select","2":"Example 1","3":"Example 2","4":"Example 3","5":"Example 4","88":"Example 5","7":"Example 6","8":"Example 7"}}');

for (key in res.products){
  $('#myList').append('<option value="'+key+'">'+res.products[key]+'</option>');
}

Which I would like to add to a simple empty <select> element using Jquery.

https://jsfiddle.net/htrdzyqo/

However the order is putting Example 5 at the bottom not in its correct place. After reading, I appreciate that object keys are not properly ordered (Sort JavaScript object by key) and that JSON keys cannot be integers (Sort JavaScript object by key). I need to preserve the object order rather than being auto-sorted. The reason being as its an ID must remain intact (so no Array alternative).

Am I missing something simple or do I need to rethink/work this?

Antony
  • 3,875
  • 30
  • 32
  • 3
    "*I need to sort by the numeric*" - but `88` is numerically larger than the other ids, so it would still end up at the bottom, which is not what you want? – Bergi May 17 '21 at 10:49
  • Does this answer your question? [Sort an array of objects based on a numeric key given as String](https://stackoverflow.com/questions/51080370/sort-an-array-of-objects-based-on-a-numeric-key-given-as-string) – freedomn-m May 17 '21 at 10:51
  • 3
    What do you mean by "*so no Array alternative*"? Yes, you should be using an array for the products if you care about order: `{"products": [ {"key": 0, "text": "Please Select"}, {"key": 2, "text": "Example 1"}, … ]}`. It's the only proper solution. – Bergi May 17 '21 at 10:52
  • Sorry you are right - I will adjust my question - I want the order preserved! – Antony May 17 '21 at 10:53

1 Answers1

3

In JSON, by definition, the name/value pairs in an object {} are unordered: They have no specific order in which they appear. In a list [] on the other hand, the order is preserved.

See also this other StackOverflow question where the answer cites the official documentation.

As @Bergi already pointed out in the comments, putting products into a list is the proper solution.

JSON.parse('{"products": [ {"key": 0, "text": "Please Select"}, {"key": 2, "text": "Example 1"}, ... ]}');

for (let product of res.products) {
  $('#myList').append('<option value="'+product.key+'">'+product.text+'</option>');
}
fravolt
  • 2,565
  • 1
  • 4
  • 19
  • Super - good example. Unfortunate it has to work this way but it is indeed the way to do it. – Antony May 17 '21 at 13:32