gunwin
gunwin

Reputation: 4832

jQuery's getJSON not maintaining original order

Having the following file (customers.json):

{"3":"Andy", "1":"Bruce", "4":"Charlie", "2":"David"}

Using this code:

jQuery.getJSON("/Customers.json", function (data) {
    console.log(data);
});

This will output the following:

{"1":"Bruce", "2":"David", "3":"Andy", "4":"Charlie"}

My Json is purposefully in alphabetical order by the name, but this this code seems to put in numerical order. Is this a feature? And how do I stop this from happening?

Whether it makes a difference, I am using Firefox 39.0

EDIT:

The real question here is, is there anyway to do this, keeping ALL the data, and maintaining the order in which is received?

Upvotes: 7

Views: 5267

Answers (5)

Blaztix
Blaztix

Reputation: 1294

If you care about the order, you must submit a list in the response JSON.

But your data is wrong in this case,

response = [{"3":"Andy"},{"1":"Bruce"},{"4":"Charlie"},{"2":"David"}]

And then:

 $.each(response ,function(index,v){
      console.log(v)
      // or
      //console.log(data[index])

      //And to get the number and name, you must do some trick 

      for (let [key, value] of Object.entries(v)) {
          console.log(number,value);
      }
 })

Best solution

You should use a key for the number, What is this number? a id, a rank?

    response = [{"id":3,"name":"Andy"},{"id":1,"name":"Bruce"},{"id":4,"name":"Charlie"},{"id":2,"name":"David"}]

And then:

 $.each(response ,function(index,value){
      console.log('Id:',value.id,'Name:',value.name);
 });

Upvotes: 0

hazzik
hazzik

Reputation: 13364

Is this a feature?

Yes kind of, the order of properties of object can be up to an implementation. Some browsers do maintain the order, some not. This is what ES5 Specification says:

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

So, as soon as you get an JavaScript object from JSON literal the order of the properties can be lost.

And how do I stop this from happening?

Is there any way to do this, keeping ALL the data, and maintaining the order in which is received?

The only real way to solve the issue is to specify the order of objects explicitly.

Upvotes: 0

guest271314
guest271314

Reputation: 1

is there anyway to do this, keeping ALL the data, and maintaining the order

Try utilizing $.map() , Array.prototype.sort() to return array of values , properties of returned object

var json = {
  "3": "Andy",
  "1": "Bruce",
  "4": "Charlie",
  "2": "David"
};
var res = $.map(json, function(val, key) {
  // keep all data, maintain order
  // return array having value as string with comma ","
  // as separator between `val` from object `key` from object
  // `val`: `Andy` , `key`: `3`
  return [ val + ", " + key ]
}).sort();
console.log(res);
document.body.textContent = res;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 1

Jan
Jan

Reputation: 5815

What your Json SHOULD look like is

[{"id":"3", "name":"Andy"}, {"id":"1", "name":"Bruce"}, {"id":"4", "name":"Charlie"}, {"id":"2", "name":"David"}]

What you're sending is a series of objects (customers), so your data structure should ideally reflect that. And transferring it as an array you can keep the order, as has already been mentioned.

Upvotes: 5

Ghazgkull
Ghazgkull

Reputation: 980

When the string that comes over the wire is converted to a Javascript object (the object representing the JSON data), what you end up with is an object like any other with properties and values. There is no ordering of properties in an object.

The object created from the JSON:

{"3":"Andy", "1":"Bruce", "4":"Charlie", "2":"David"}

is identical to an object created with this Javascript:

obj = {}; // <-- Not an array!
obj[1] = 'Andy';
obj[2] = 'Bruce';
obj[3] = 'Charlie';
obj[4] = 'David';

If you want to output the object in order of the property values, you'll need to first load the values into an array and then sort the array alphabetically.

Something like:

var sorted = [];
for (var prop in data) {
    if (data.hasOwnProperty(prop)) {
        sorted(json[prop]);
    }
}
sorted.sort();
console.log(sorted);

Upvotes: 0

Related Questions