60318

How do i reverse JSON in JavaScript?

Question:

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

I looked on here, and someone had the same sort of question, but the "checked" correct answer was that it will be different on IE if the item is deleted, which would be fine. My issue is, those items above are stored, but when i go and grab them, iterate, and return, the items are reversed and the created is at the 0 index and task is at 1. Also, i need to return this as JSON.

Here is my basic JS (value == an <em>int</em> the user is passing in):

outputJSON = {}; for(x in json[value]){ outputJSON[x] = _objectRevival(json[value][x]); } return outputJSON;

That returns:

created: Mon Dec 06 2010 15:09:40 GMT-0800 (Pacific Standard Time) task: "test"

Answer1:

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) } }

Answer2:

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"].

Answer3:

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"]

<strong>Update:</strong> 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;

Answer4:

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.

Recommend

  • Edge-case: When (only) reversing order of template parameters in specialization, can non-specialized
  • How can I write a recursive function to reverse a linked list?
  • (Play 2.5) How do you define json format for type alias of an Option?
  • Creating a C++ function that calls other Lua function
  • Single django queryset to get n adjacent items
  • How do I bind multiple properties in an Android layout element
  • Unzip archive in .Net CORE 1.0
  • Telegram bot API - Inline bot getting Error 400 while trying to answer inline query
  • Python PIL to extract number from image
  • Select value from xtype selection type checkbox CQ5
  • CodeIgniter URI Parameter is partially bypassing an “if” statement
  • Javascript CORS - No 'Access-Control-Allow-Origin' header is present
  • Exception creating JSON with LINQ
  • How to use function wrapper in mustache.php?
  • opencv display image without x server
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • htaccess add www if not subdomain, if subdomain remove www
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • JSON response opens as a file, but I can't access it with JavaScript
  • Play WS (2.2.1): post/put large request
  • Different response to non-authenticated users and AJAX calls
  • req.body is undefined - nodejs
  • Accessing IRQ description array within a module and displaying action names
  • Modifying destination and filename of gulp-svg-sprite
  • Importing jscolor library in angular 2
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • Proper way to use connect-multiparty with express.js?
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Authorize attributes not working in MVC 4
  • Is it possible to post an object from jquery to bottle.py?
  • Busy indicator not showing up in wpf window [duplicate]
  • Sorting a 2D array using the second column C++
  • Conditional In-Line CSS for IE and Others?
  • Python/Django TangoWithDjango Models and Databases
  • java string with new operator and a literal
  • Net Present Value in Excel for Grouped Recurring CF