Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse the JSON Array stored in javascript variable

I have a json array stored in variable in format below:

{"info": 
[ {"typeid": "877", "recid": "10", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "877", "recid": "11", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "459", "recid": "3", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "459", "recid": "4", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "456", "recid": "5", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "456", "recid": "6", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"}
]}

I want to reverse the inner JSON array for info.Like this

{"info": 
[ {"typeid": "456", "recid": "6", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "456", "recid": "5", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "459", "recid": "4", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "459", "recid": "3", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "877", "recid": "11", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"},
  {"typeid": "877", "recid": "10", "repeaterid": "0",  "pageid": "26966", "maxrecords": "1"}
]}

How can i achieve this.

enter image description here

like image 691
Milind Anantwar Avatar asked Feb 11 '14 13:02

Milind Anantwar


3 Answers

Use the array reverse method of Javascript:

var objAssetSelection = $.parseJSON(strAssetSelection);
objAssetSelection.info.reverse();
console.log(objAssetSelection);
like image 68
Barmar Avatar answered Oct 10 '22 13:10

Barmar


Did you tried myObject.info.reverse() ?

More about Javascript Array Reverse

like image 22
Mihai Matei Avatar answered Oct 10 '22 13:10

Mihai Matei


and simply (JQuery needed) :

function test() {
    var myArray = [1, 2, 3, 4];
    var myReversedArray = new Array();
    $(myArray).each(function (key) {
        myReversedArray.unshift(myArray[key]);
    });
    myArray = myReversedArray;
    $(myArray).each(function (key) {
        console.log(myArray[key]);
    });
}
like image 43
To delete profile Avatar answered Oct 10 '22 14:10

To delete profile