sort json object in javascript

JavascriptJsonSorting

Javascript Problem Overview


For example with have this code:

var json = {
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    },
    "user3" : {
        "id" : 1
    }
}

How can I sort this json to be like this -

var json = {
    "user3" : {
        "id" : 1
    },
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    }
}

I sorted the users with the IDs..
I don't know how to do this in javascript..

Javascript Solutions


Solution 1 - 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}];

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

if(JSON.stringify(Object.keys(pcOrGroup).sort()) === JSON.stringify(Object.keys(orGroup)).sort())
{
    return true;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjulianView Question on Stackoverflow
Solution 1 - JavascriptRocket HazmatView Answer on Stackoverflow
Solution 2 - JavascriptVyacheslav CotrutaView Answer on Stackoverflow
Solution 3 - JavascriptKatana314View Answer on Stackoverflow
Solution 4 - Javascriptuser4081130View Answer on Stackoverflow