1

I have a JSON object that is sorted alphabetically based on the value rather than the key. However when I use _.each to inject the object into the form $select, the object is resorting it based on the key. Does anyone know how I can prevent this.

var $select = $("#tunnel-list");
        var tpl = _.template('<option value="<%= id %>"><%= name %></option>');
        _.each(tunnels, function(name, index) {
            console.log(name, index)
            $select.append(tpl({id: index, name:  name}));
        });
ByteWelder
  • 5,464
  • 1
  • 38
  • 45
KoalaKid
  • 232
  • 2
  • 11

2 Answers2

1

You might be talking about a JavaScript Object, since JSON is a string representation of data that resembles to JavaScript syntax.

If you have an object, its order of elements cannot be guaranteed. You can only sort it by using an array that will require you to change your data structure.

Hope the following link answers your question as well: Does JavaScript Guarantee Object Property Order?

Community
  • 1
  • 1
Steven Tsao
  • 90
  • 1
  • 10
0

A javascript object is just a hashmap of key/value pairs, it cannot be sorted (unlike an array). On the other hand you can "Sort" a JSON object on a file by moving characters around. But when you read the JSON as an object and load it into memory, you lose this fake "sortedness" and traverse it's keys based on how the JS engine was implemented.

the underscore _.each function is just a wrapper for a for loop that runs over your key/value pairs and runs a function on them. you should be using _.each to traverse arrays.

TL;DR : you can't sort objects

but what you can do it transfer values to an array and sort it there by using the native Array.prototype.sort function.

svarog
  • 9,477
  • 4
  • 61
  • 77