Reputation: 82241
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.
Upvotes: 8
Views: 37161
Reputation: 6502
Successfully Working Converting JSON Array to Reverse JSON Array 101% Working
var ActualArray = [{
"bag":'large',
"color":'blue'
},{
"bag":'small',
"color":'red'
},{
"bag":'medium',
"color":'green'
},{
"bag":'large',
"color":'pink'
}]
var ReverseArray = [];
var length = ActualArray.length;
for(var i = length-1;i>=0;i--){
ReverseArray.push(ActualArray[i]);
}
console.log("actual array");
console.log(JSON.stringify(ActualArray));
console.log("reverse array");
console.log(JSON.stringify(ReverseArray));
Your Log will be like below
actual array
[{"bag":"large","color":"blue"},{"bag":"small","color":"red"},{"bag":"medium","color":"green"},{"bag":"large","color":"pink"}]
reverse array
[{"bag":"large","color":"pink"},{"bag":"medium","color":"green"},{"bag":"small","color":"red"},{"bag":"large","color":"blue"}]
Upvotes: 0
Reputation: 781058
Use the array reverse
method of Javascript:
var objAssetSelection = $.parseJSON(strAssetSelection);
objAssetSelection.info.reverse();
console.log(objAssetSelection);
Upvotes: 21
Reputation: 382
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]);
});
}
Upvotes: 2
Reputation: 3362
var sorted=yourobject.info.sort(function(a,b){return a.typeid-b.typeid});
Ref: http://www.w3schools.com/jsref/jsref_sort.asp
Upvotes: 2
Reputation: 24276
Did you tried myObject.info.reverse()
?
More about Javascript Array Reverse
Upvotes: 6