Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse object in jQuery.each

HTML:

<input id="sdata" type="hidden" value='{"1651":["12","1"],"1650":["30","0"],"1649":["20","0"],"1648":["13","2"],"1647":["11","0"],"1646":["10","0"],"1645":["12","0"],"1644":["8","0"],"1643":["16","1"],"1642":["10","1"],"1641":["10","0"],"1640":["18","3"]}' />

JS:

var data = $.parseJSON($('#sdata').val());
$.each(data, function(id, sc) {
    alert(id);
}

OUT: 1640, 1641, 1642, ..., 1651

How to make it in reverse order (ex. 1651, 1650...)?

like image 709
Sladex Avatar asked Jan 29 '11 18:01

Sladex


3 Answers

As it is, you can't in any reliable manner. Because you are enumerating an Object, there is never a guaranteed order.

If you want a guaranteed numeric order, you would need to use an Array, and iterate backwards.


EDIT: This will convert your Object to an Array, and do a reverse iteration.

Note that it will only work if all the properties are numeric.

var data = $.parseJSON($('#sdata').val());
var arr = [];

for( var name in data ) {
    arr[name] = data[name];
}
var len = arr.length;
while( len-- ) {
    if( arr[len] !== undefined ) {
        console.log(len,arr[len]);
    }
}
like image 71
user113716 Avatar answered Nov 10 '22 05:11

user113716


There is another solution, a fairly easy one:

$(yourobject).toArray().reverse();

That's it.

like image 11
xorinzor Avatar answered Nov 10 '22 05:11

xorinzor


I tried this and it worked perfectly for me.

var data = $.parseJSON($('#sdata').val());
$.each(data.reverse(), function(id, sc) {
    alert(id);
});

The only change is the "reverse()" in line 2.

like image 8
Araya Yamir Avatar answered Nov 10 '22 05:11

Araya Yamir