0

Since it is not possible to get a JSON file with the original order, I'd like to sort it in JS again. The file looks like this:

{
    "index": 5,
    "timestamp": 1570438008,
    "data": {
        "12": [
            "Title 2",
            "Description 2"
        ],
        "10": [
            "Title 1",
            "Description 1"
        ]
    }
}

If I access this JSON file now from JS, I get another order than the original:

$.ajax({
    url: '../json/smiirl_data.json',
    dataType: 'json',
    success: function(response) {
        console.log(response['data']);
    }
});

console.log from JS shows:

{
    "10": [
        "Title 1",
        "Description 1"
    ],
    "12": [
        "Title 2",
        "Description 2"
    ]
}

Is it possible to sort (title descending) it? I need the orignal order (12, 10).

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
c3560231
  • 9
  • 5
  • Key order is not guaranteed. If you need them sorted, return an array of `[ id, data ]` pairs. – Mr. Polywhirl Oct 07 '19 at 11:40
  • 1
    @Mr.Polywhirl in ES6 compliant environments it *is* but then you cannot have numeric keys in reverse order. In non-ES6 compliant environments, you just don't have a guarantee. So it's a lose-lose situation. As always, the suggestion is that if you want ordered objects, use an array. – VLAZ Oct 07 '19 at 11:42
  • @VLAZ Can you give me an example for my code? – c3560231 Oct 07 '19 at 11:45
  • @Anuga I've tried this but I couldn't get it work. Can you give me an example for my code :)? – c3560231 Oct 07 '19 at 11:51
  • The real question is why do you want the order of your data to be a certain way? – Lee Taylor Oct 07 '19 at 11:56
  • @LeeTaylor I create some html content from this JSON file and the content should be sorted in a specific order for this. – c3560231 Oct 07 '19 at 11:58
  • @c3560231 Do you want to maintain the original order or sort descending? – Sudhakar Ramasamy Oct 07 '19 at 11:58
  • @SudhakarRS It doesn't matter. I sorted the JSON file with php before. So if it is possible to maintain the original, I would be happy. – c3560231 Oct 07 '19 at 12:04
  • @c3560231 'Object.entries(response.data).sort((a,b)=>{return b[0]-a[0]})' will sort – Sudhakar Ramasamy Oct 07 '19 at 12:28

3 Answers3

2

at first you need to serialize object to array after that you use sort function to sort it.

var array = [],
    data = response['data'];

    for (var array in data ) {
         array.push([array, data[vehicle]]);
    }

     array.sort(function(a, b) {
        return b[1] - a[1];
     });
0

Because objects are not always guaranteed to maintain its order, and JSON does not support the Map class which guarantees the order, you should use an array instead, where there are two elements: the key and the value.

For example:

"data": [
  [12, ["Title 2", "Description 2"],
  [10, ["Title 1", "Description 1"]
]

The you can access it like:

for(let item of myJSON.data)
{
  console.log('Key:', item[0]);
  console.log('Value:', item[1]);
}
E. Zacarias
  • 598
  • 6
  • 19
0

To guarantee order, re-structure your data to be a 2-dimensional array.

You can create an index map, and lookup function to make the data easier to query.

let data = {
  "index": 5,
  "timestamp": 1570438008,
  "data": [
    [ "12", [ "Title 2", "Description 2" ] ],
    [ "10", [ "Title 1", "Description 1" ] ]
  ]
}

let indexMap = indexLookupMap(data.data); // Build an index
console.log(lookupEntry(data.data, indexMap, '10')); // Find entry with id '10'

data.data.forEach(entry => {
  console.log(`key => ${entry[0]}, value => ${entry[1].join(', ')}`);
})

function lookupEntry(data, indexMap, id) {
  return data[indexMap[id]][1];
}

function indexLookupMap(data) {
  return data.reduce((dict, entry, idx) => Object.assign(dict, { [entry[0]]: idx }), {});
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132