sort json object in javascript sort json object in javascript json json

sort json object in javascript


First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.

Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.

One option might be to make your data look like this:

var json = [{    "name": "user1",    "id": 3}, {    "name": "user2",    "id": 6}, {    "name": "user3",    "id": 1}];

Now you have an array of objects, and we can sort it.

json.sort(function(a, b){    return a.id - b.id;});

The resulting array will look like:

[{    "name": "user3",    "id" : 1}, {    "name": "user1",    "id" : 3}, {    "name": "user2",    "id" : 6}];


Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {    return '[object Object]' === Object.prototype.toString.call(v);};JSON.sort = function(o) {if (Array.isArray(o)) {        return o.sort().map(JSON.sort);    } else if (isObject(o)) {        return Object            .keys(o)        .sort()            .reduce(function(a, k) {                a[k] = JSON.sort(o[k]);                return a;            }, {});    }    return o;}

It can be used as follows:

JSON.sort({    c: {        c3: null,        c1: undefined,        c2: [3, 2, 1, 0],    },    a: 0,    b: 'Fun'});

That will output:

{  a: 0,  b: 'Fun',  c: {    c2: [3, 2, 1, 0],    c3: null  }}


In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]var sortedKeys = [...]for (var i = 0; i < sortedKeys.length; i++) {  var key = sortedKeys[i];  addObjectToTable(json[key]);}