Antony
Antony

Reputation: 4344

Preserve javascript key order when they're integers

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?

Upvotes: 1

Views: 340

Answers (1)

fravolt
fravolt

Reputation: 3001

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>');
}

Upvotes: 3

Related Questions