0

Currently, I map my JSON file like this:

var sortedData = $.map(response.data, function(data, index) {
    return [data];
});

This works fine. But the key (index) is missing. How can I add it?

Content of the JSON file:

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

After $.map I'd like to sort it (data attribute). I did it like this:

sortedData.sort(function(a, b) {
    return (b[3] < a[3]) ? -1 : 1;
});

Expected output:

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

.. and NOT like this:

"10": [
    "Title 1",
    "Description 1"
],
"12": [
    "Title 2",
    "Description 2"
]
c3560231
  • 9
  • 5

1 Answers1

0

You are returning [data] which return you the value of key data, instead you should return only data which will return value of all keys including index.

var jsonContent = {
    "index": 5,
    "timestamp": 1570438008,
    "data": {
        "12": [
            "Title 2",
            "Description 2"
        ],
        "10": [
            "Title 1",
            "Description 1"
        ]
    }
};
var sortedTicketsDesc = $.map(jsonContent, function(data, index) {
    return data;
});
console.log(sortedTicketsDesc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
  • It worked BUT I can't sort the content (data) now. I used sortedTicketsDesc.sort(function(a, b) { return (b[3] < a[3]) ? -1 : 1; }); – c3560231 Oct 07 '19 at 13:28
  • can you post your sorting code and on which attribute you are sorting and what is expected output? – Bhushan Kawadkar Oct 07 '19 at 13:30
  • Before I changed my code to your solution, the sorting part worked fine too. – c3560231 Oct 07 '19 at 13:39
  • Error: sortedTicketsDesc[2].sort is not a function – c3560231 Oct 07 '19 at 13:49
  • jsonobject does not preserve the sorting order on most of the browser and it sorts automatically by its alphabetical order. check this https://stackoverflow.com/questions/14606640/chrome-and-ie-sorts-json-object-automatically-how-to-disable-this and https://github.com/nlohmann/json/issues/727 – Bhushan Kawadkar Oct 09 '19 at 04:44