Arranging a JSON data structure (varied sequence in Firefox)

Looking to organize a JSON Object based on the key - Chrome maintains the order I need, but Firefox does not.

Below is an example of my JSON object:

{
  "media": {
    "1387185503": {
      "id_profil": "7256",
      "photo_profil": "http://www.mupiz.com/7256/picture",
      "phrase_feed": "a ajouté une nouvelle vidéo",
      "nom_media": "Jam a la casserole",
      "nom_profil": "Camille Boullier de Branche",
      "url_profil": "camille-boullier-de-branche",
      "streaming": "<iframe width=\"270\" height=\"200\" src=\"http://www.youtube.com/embed/K6i_avCwsvQ?html5=1\" frameborder=\"0\" allowfullscreen></iframe>",
      "url_media": "http://www.mupiz.com/camille-boullier-de-branche/video/jam-a-la-casserole"
    },
    "1387185460": {
      "id_profil": "7256",
      "photo_profil": "http://www.mupiz.com/7256/picture",
      "phrase_feed": "a ajouté une nouvelle vidéo",
      "nom_media": "festival silhouette 2010 avec IGIT",
      "nom_profil": "Camille Boullier de Branche",
      "url_profil": "camille-boullier-de-branche",
      "streaming": "<object width=\"270px\" height=\"200px\" ><param name=\"movie\" value=\"http://www.dailymotion.com/swf/xet02y&related=0&colors=background:000000;foreground:FFFFFF;special:88868A;\"></param><param name=\"wmode\" value=\"transparent\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowScriptAccess\" value=\"always\"></param><embed src=\"http://www.dailymotion.com/swf/xet02y&related=0&colors=background:000000;foreground:FFFFFF;special:88868A;\" type=\"application/x-shockwave-flash\" width=\"270\" wmode=\"transparent\"  height=\"200\" allowfullscreen=\"true\" allowscriptaccess=\"always\"></embed></object>",
      "url_media": "http://www.mupiz.com/camille-boullier-de-branche/video/festival-silhouette-2010-avec-igit"
    },
    "1385912810": {
      "id_profil": "36541",
      "photo_profil": "http://www.mupiz.com/36541/picture",
      "phrase_feed": "a ajouté une nouvelle chanson",
      "nom_media": "Sans titre",
      "nom_profil": "Eve IBK",
      "url_profil": "evelyne-zyss",
      "streaming": "\r\n  <div class=\"playerMedia\" onclick=\"InlinePlayer(this)\" data-url=\"http://www.mupiz.com/mp3/36541/mp3_85725.mp3\" data-id=\"mp3_85725.mp3\">Sans titre</div>\r\n",
      "url_media": "http://www.mupiz.com/evelyne-zyss/"
    }, .....

I aim to sort this section of the JSON object by timestamp in ascending order rather than descending.

Any suggestions?

Thank you

Answer №1

When 'strigify' numbers in JSON, browsers auto-sort the properties:

For instance, both Chrome and Firefox will behave similarly with this code snippet:

 var an_obj = { "4": "d", "1": "a", "2": "c"};
 alert(Object.keys(an_obj)); //will alert 1, 2, 4

However, when dealing with specific sample JSON data:

Chrome:

var an_obj = { "1387185460": "a", "1387185503": "b", "1385912810": "c"};
alert(Object.keys(an_obj)); // will alert "1385912810, 1387185460, 1387185503"

On the other hand, Firefox maintains the original order:

var an_obj = { "1387185460": "a", "1387185503": "b", "1385912810": "c"};
 alert(Object.keys(an_obj)); // will alert "1387185460, 1387185503, 1385912810"

This discrepancy exists due to Firefox's sorting algorithm behavior, which only comes into play when the first 3 characters are not identical.

In another example:

Chrome:

  var value2 = {"1003":1, "1001":2, "1000":3};
  alert(Object.keys(value2)); // will alert 1000, 1001, 1003

Firefox, on the other hand, preserves the initial sequence:

 var value2 = {"1003":1, "1001":2, "1000":3};
 alert(Object.keys(value2)); // will alert 1003, 1001, 1000

This issue is acknowledged by the Firefox team and is related to enumeration ordering as part of ES6. It is anticipated to be resolved in ES7 implementation.

To address your current dilemma, consider implementing the following approach:

var arr = {
        "media": {
            "1387185503": {
                // Data here
            },
            "1387185460": {
                // Data here
            },
            "1385912810": {
               // Data here
            }
        }
    };
 var properties=Object.keys( arr.media).sort();
 arr.media = properties.reduce(function(res, prop){
           res[prop] = arr.media[prop];
           return res;
       },{});

Alternatively, you could implement toJSON like so:

arr.media.toJSON = function(){
            var newMedia = properties.reverse().reduce(function(res, prop){
                res[prop] = arr.media[prop];
                return res;
            },{});
           return newMedia;
       };
 var newSortedObject =(JSON.stringify(arr.media));

We hope this provides some clarity and assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The operation was computed twice

Below is an example: test.html <!DOCTYPE html> <html ng-app ng-controller="AppController"> <head> <script type="text/javascript" src="angular.js"></script> <script type="text/javascript" src="script1 ...

On Internet Explorer 9, the window.open function is causing a new window to open up with

I am having an issue with redirecting my form to another page in a new window using window.open(). The problem I'm encountering is that when the new window opens, it appears blank and the original browser window redirects to the intended page for the ...

When the screen is at mobile width, elements with the class "Responsive" are hidden using the display:none; property. These elements can be

Hey there! So, I've got this cool interactive banner on my website. It features 2 slider sections with some awesome products on the right side. The layout is responsive, meaning that when you switch to a mobile screen size (around 515px or less), the ...

Exploring nested JSON structures in CosmosDB database

We are currently utilizing CosmosDB SQLAPI in one of our applications, and I am running queries using Azure Storage Explorer. The JSON structure that I am working with is proving to be challenging to query. { "countyid": 0, "data": [ [ ...

What is the best way to modify a constant array in Angular?

Hello team, I'm fresh to working with angular and I have a TypeScript file that contains a list of heroes: export const HEROES: Hero[] = [ { id: 11, name: 'Dr Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombas ...

Checking for non-overlapping number ranges in an array in React/Javascript before submitting

I am faced with a challenge involving a list of values containing start and end address values. I need to ensure that when submitting these values, there are no existing ranges or overlaps within them. [ { "id": 23, "startAddress&quo ...

Is it possible to configure Nginx to provide HTTPS on port 10000 and implement Basic Auth for an Express app?

My Linux NodeJS/Express application is designed to serve a text file located at http://example.com/secret.txt. I am looking to restrict access to this file only over HTTPS on port 10000 with Basic Auth security measures in place. It's important to no ...

User form not triggering post requests

I have a unique react blog application embedded with a form for submitting intriguing blog posts. The setup includes a server, routes, model, and controllers for fetch requests. Surprisingly, everything functions impeccably when tested on Postman. However, ...

Is there a way to output JSON objects and array elements programmatically?

Within the Result String, I have a complete dataset that needs to be parsed. My goal is to extract and print the Current Conditions values. current_condition": [ {"cloudcover": "75", "humidity": "71", "observation_time": "06:55 AM", "precipMM": "0.6", "pr ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

JavaScript backspace function not functioning correctly

I'm having issues with the Backspace keycode not working. I've tested it in IE and Google Chrome, but it's not displaying anything in the console or the alert. Here is the code snippet: $(document).keypress(function(e) { con ...

After updating to Eclipse Neon, the resolution of Javax.Json is not working properly

After downloading the latest version of Eclipse, Neon for JEE, I decided to follow the advice from Eclipse and overwrite my workspace settings. However, upon opening the new Eclipse, I encountered an error with my maven projects: The import javax.Json ...

Tips for combining tables and outputting as JSON format?

I currently have PostgreSQL set up with the following table structure: CREATE TABLE "objs"("number" Integer,"name" Text NOT NULL, "price" Text NOT NULL ); CREATE TABLE "users"("name" Text NOT NUL ...

endless cycle of scrolling for div tags

My goal is to incorporate a tweet scroller on I believe it uses the tweet-scroller from Unfortunately, this link seems broken as the demo is not functioning. I searched for an alternative solution and came across http://jsfiddle.net/doktormolle/4c5tt/ ...

Displaying elapsed time in JavaScript (Node.js)

Looking for a way to convert a date time or time-stamp format like 2015-12-18 07:10:54 into a relative time, such as "2 hours ago." I attempted the code provided, but it seems to consistently show an incorrect estimation of "8 days ago." function convert ...

"Unlocking the power of AngularJS translate: A step-by-step

I'm seeking answers to two questions. 1) How can I utilize angularjs translate with ng-repeat? Although my Json file works fine, the text does not display when using ng-repeat. Here is a snippet from my json: "rules":{ "points":[ {"t ...

Unable to view PDF files on mobile devices within Ionic app, only accessible through browser interface

I utilized the angularjs-pdf library to display a PDF document from a remote source within a mobile app created with Ionic Framework. While it successfully displays the PDF in the browser, on mobile devices it only shows a blank screen. In addition, I re ...

Can you provide steps on loading JSON data into a JavaScript web application and then randomly selecting a word from it?

I have a text file called words.json with a long list of words, organized in alphabetical and length order. The structure looks like this: {"3":["ace","act","add","ado","ads"], "4":[...], ...} (I have used ellipsis for brevity) How do I go about loadin ...

Accessing values from an array within a JSON object using jqGrid

Here is an example of my JSON data: [{"codDiretor":"123", "nomeDiretor":"Nome do Diretor", "data":"29/01/2014", "documentos":[{"codDocumento":"1", "nomeDocumento":"Primeiro Doc"}, {"codDocumento":"2","nomeDocumento":"Segundo Doc"}] ...