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...)?
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]);
}
}
There is another solution, a fairly easy one:
$(yourobject).toArray().reverse();
That's it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With