Skip to content Skip to sidebar Skip to footer

How Do I Reverse Json In Javascript?

[ {'task':'test','created':'/Date(1291676980607)/'}, {'task':'One More Big Test','created':'/Date(1291677246057)/'}, {'task':'New Task','created':'/Date(1291747764564)/'}

Solution 1:

The order of the properties of an object is undefined. It is not possible to force them in a specified order. If you need them in a specific order, you can build this structure reliably using arrays:

var values = [
   [["task", "test"],              ["created", "/Date(1291676980607)/"]],
   [["task", "One More Big Test"], ["created", "/Date(1291677246057)/"]],
   [["task", "New Task"],          ["created", "/Date(1291747764564)/"]]
];

Then you can iterate over your structure like this:

for (var i = 0; i < values.length; i++) {
    for (var k = 0; k < values[i]; k++) {
        // values[i][k][0] contains the label (index 0)// values[i][k][1] contains the value (index 1)
    }
}

Solution 2:

To enforce a particular order for your output just replace json[value] in your for loop with an array of the object properties in the order you want to display them, in your case ["task", "created"].

Solution 3:

The problem is that javascript objects don't store their properties in a specific order. Arrays on the other do (hence why you can get something consistent from json[0], json[1], json[2]).

If your objects will always have "task" and "created", then you can get at them in any order you want.

json[value]["task"]

and

json[value]["created"]

Update: This should work with your existing code. Before sending the json object:

var before = [
   {"task":"test","created":"/Date(1291676980607)/"},
   {"task":"One More Big Test","created":"/Date(1291677246057)/"},
   {"task":"New Task","created":"/Date(1291747764564)/"}
];
var order = [];
for (var name in before[0]) {
   order.push(name); // puts "task", then "created" into order (for this example)
}

Then send your json off to the server. Later when you get the data back from the server:

var outputJSON = {};
for (var x in order) {
   if (order.hasOwnProperty(x)) {
      outputJSON[order[x]] = _objectRevival(json[value][order[x]]); // I'm not sure what _objectRevival is...do you need it?
   }
}
return outputJSON;

Solution 4:

var items = ["bag", "book", "pen", "car"];
items.reverse();

This will result in the following output:

car , pen, book, bag

Even if you have JSON array it will reverse.

Post a Comment for "How Do I Reverse Json In Javascript?"