0

I have a JSON string that I parse to a JSON Object with the json2.js library.

var parsed = JSON.parse(jsonstring);

Afterwards I do some magic to show that data to the user. The contained data are several messages. In all browsers they are sorted in the correct order. However in IE9 the order is reversed. From old messages to new messages instead of the new messages first.

I read that the order of the parsing result is not fixed and depends on the JavaScript version. So I tried to sort the items the way I want, but it's not working.

I currently do:

var parsed = JSON.parse(feeds);
parsed = sortJSON(parsed, "created");

function sortJSON(data, key) {
     return data.sort(function(a, b) {
            var x = a[key]; var y = b[key];
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
}

But I get the following error in the console:

Object doesn't support property or method 'sort'

So my guess is that my sorting method isn't correct because of the structure of the JSON object. So the question is 'What do I need to alter in my sort method so that it works?

Structure of my json string:

 {"<ID>":{"text":"...","user":"...","created":"<date>",
 "subject":"","url":"...","img_class":".."},

 "<ID>":{"text":"...","user":"...","created":"<date>","subject":"",
 "url":"...","img_class":"..."}, <MORE MESSAGES> 
 }
Stephan Celis
  • 2,492
  • 5
  • 23
  • 38
  • 4
    Objects are not arrays. In particular, objects are unordered. – SLaks May 06 '13 at 13:56
  • 2
    Instead of returning your results as a single JSON object, return them as an array. That is, the server response will look like `[{"foo"},{"goo"},...]` instead of `{{"foo"},{"goo"},...}` – Bucket May 06 '13 at 13:57

2 Answers2

0

OnlyArray could be sorted, not Object. You are not guaranteed to receive back an ordered object when you sort it.

Look at this answer for a working solution Sorting JavaScript Object by property value

Community
  • 1
  • 1
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
0

sort only works on Arrays and since your object is a hash, you could do something like this instead:

var items = [];
for (var k in data) {
    items.push({
        id: k,
        original: data[k]
    });
}
items.sort(...);
cutsoy
  • 10,127
  • 4
  • 40
  • 57