JSON Object does not maintain order of insertion. This post discusses how to sort JSON object by key or value.

In order to sort JSON objects, we have to take help of Arrays. Arrays maintain an order of insertion. Moreover, it provides native sort() method to sort array elements.

Sort JSON Object by Key:

Following sortByKey() function takes JSON Object as an input and returns JSON Array which is sorted by key.

	
function sortByKey(jsObj){
  	var sortedArray = [];
  	
  	// Push each JSON Object entry in array by [key, value]
  	for(var i in jsObj)
  	{
		sortedArray.push([i, jsObj[i]]);
	}

	// Run native sort function and returns sorted array.
	return sortedArray.sort();
}

var jsObj = {};
jsObj.e = "elephant";
jsObj.b = "ball";
jsObj.d = "dog";

var sortedbyKeyJSONArray = sortByKey(jsObj);
console.table(sortedbyKeyJSONArray);
//	(index)		 0		  1
//		0		"b"		"ball"
//		1		"d"		"dog"
//		2		"e"		"elephant"
	

Sort JSON Object by Value:

We will create JSON Array of [jsonValue, jsonKey] from JSON Object. Then, we will sort JSON Array using sort() function. Checkout folllwing example.

	
function sortByValue(jsObj){
  	var sortedArray = [];
  	for(var i in jsObj)
  	{
  		// Push each JSON Object entry in array by [value, key]
		sortedArray.push([jsObj[i], i]);
	}
	return sortedArray.sort();
}
var jsObj = {};
jsObj.e = "elephant";
jsObj.b = "ball";
jsObj.d = "dog";

var sortedbyValueJSONArray = sortByValue(jsObj);
console.table(sortedbyValueJSONArray);
//	(index)		 0		  	 1
//		0		"ball"		"b"
//		1		"dog"		"d"
//		2		"elephant"	"e"

	

References

Sort Arrays