2

I'm having JSON object

var x=[{@Name:'test 1',@Sort:'1',@Status:'yes'},
       {@Name:'test 2',@Sort:'5',@Status:'yes'},
       {@Name:'test 3',@Sort:'4',@Status:'no'},
       {@Name:'test 5',@Sort:'2',@Status:'no'}]

I'm trying to sort the obj by @Sort,@Name and @Status.

    var orderBy="@Sort";
    x.sort(_sortObj(orderBy));

    function _sortObj(orderBy){
        return function(a,b){
           return (a[orderBy]<b[orderBy])?1:0....etc
        }
    }

It works fine in Firefox and Chrome...

But throws error in IE 7/8 as "number expected" on line

  x.sort(_sortObj(orderBy));

I'm not sure what's going on and it will be great if anyone sort this out properly.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Nithish
  • 253
  • 2
  • 4
  • 16
  • duplicate of http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value – jbabey Mar 26 '12 at 16:26
  • @jbabey I don't think it's necessarily a duplicate. The algorithm is correct, but it's throwing an exception in IE. – Brandan Mar 27 '12 at 13:09

4 Answers4

1

That is not a JSON object. The property names and values MUST be enclosed in "double quotes".

This is probably the reason for the error in older IE, it doesn't understand the @ being there.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

In addition to Kolink's answer, IE might not be coercing your string-y numbers into actual numeric objects for the < comparison. You can perform that coercion yourself by multiplying by 1:

return (a[orderBy]*1 < b[orderBy]*1) ? 1 : 0;
Brandan
  • 14,735
  • 3
  • 56
  • 71
  • How are you receiving this JSON from your API? As a string? If so, you can probably perform a regular expression replacement of the malformed attributes. – Brandan Mar 27 '12 at 13:14
0

I got solved this issue using the below Sorting plugin,

http://www.thomasfrank.se/downloadableJS/objSort.js

Thanks guys for helping me around

Nithish
  • 253
  • 2
  • 4
  • 16
0

i am having the same issue with you, and seems like it's an IE issue, maybe you can try this:

var orderBy="@Sort";
x.sort(_sortObj(orderBy));

function _sortObj(orderBy){
    return function(a,b){
       var aa = a,bb = b;
       return (aa[orderBy]<bb[orderBy])?1:0....etc
    }
}

you can find some help from here:http://www.zachleat.com/web/array-sort/comment-page-1/#comment-3941

YuC
  • 1,787
  • 3
  • 19
  • 22