Sorting a JavaScript object by property name

JavascriptSortingObject

Javascript Problem Overview


I've been looking for a while and want a way to sort a Javascript object like this:

{
	method: 'artist.getInfo',
	artist: 'Green Day',
	format: 'json',
	api_key: 'fa3af76b9396d0091c9c41ebe3c63716'
}

and sort is alphabetically by name to get:

{
	api_key: 'fa3af76b9396d0091c9c41ebe3c63716',
	artist: 'Green Day',
	format: 'json',
	method: 'artist.getInfo'
}

I can't find any code that will do this. Can anyone give me some help?

Javascript Solutions


Solution 1 - Javascript

UPDATE from the comments: > This answer is outdated. In ES6 objects keys are now ordered. See this question for an up-to-date answer

By definition, the order of keys in an object is undefined, so you probably won't be able to do that in a way that is future-proof. Instead, you should think about sorting these keys when the object is actually being displayed to the user. Whatever sort order it uses internally doesn't really matter anyway.

By convention, most browsers will retain the order of keys in an object in the order that they were added. So, you could do this, but don't expect it to always work:

function sortObject(o) {
	var sorted = {},
	key, a = [];

	for (key in o) {
		if (o.hasOwnProperty(key)) {
			a.push(key);
		}
	}

	a.sort();

	for (key = 0; key < a.length; key++) {
		sorted[a[key]] = o[a[key]];
	}
	return sorted;
}

Solution 2 - Javascript

this function takes an object and returns a sorted array of arrays of the form [key,value]

function (o) {
   var a = [],i;
   for(i in o){ 
     if(o.hasOwnProperty(i)){
         a.push([i,o[i]]);
     }
   }
   a.sort(function(a,b){ return a[0]>b[0]?1:-1; })
   return a;
}

The object data structure does not have a well defined order. In mathematical terms, the collection of keys in an object are an Unordered Set, and should be treated as such. If you want to define order, you SHOULD use an array, because an array having an order is an assumption you can rely on. An object having some kind of order is something that is left to the whims of the implementation.

Solution 3 - Javascript

Just use sorted stringify() when you need to compare or hash the results.

Solution 4 - Javascript

// if ya need old browser support
Object.keys = Object.keys || function(o) {  
var result = [];  
for(var name in o) {  
    if (o.hasOwnProperty(name))  
      result.push(name);  
}  
    return result;  
};

var o = {c: 3, a: 1, b: 2};
var n = sortem(o);

function sortem(old){
  var newo = {}; Object.keys(old).sort().forEach(function(k) {new[k]=old[k]});
  return newo;
}

// deep
function sortem(old){
  var newo = {}; Object.keys(old).sort().forEach(function(k){ newo[k]=sortem(old[k]) });
  return newo;
}
sortem({b:{b:1,a:2},a:{b:1,a:2}})

Solution 5 - Javascript

Here is a one-liner for you.

Array.prototype.reduce()

let data = {
    method: 'artist.getInfo',
    artist: 'Green Day',
    format: 'json',
    api_key: 'fa3af76b9396d0091c9c41ebe3c63716'
};

let sorted = Object.keys(data).sort().reduce( (acc, currValue) => {
    acc[currValue] = data[currValue];
    return acc;
}, {});

console.log(sorted);

Good luck!!

Solution 6 - Javascript

ES5 Compatible:

function sortByKey(obj) {
	var keys = Object.keys(obj);
	keys.sort();
	var sorted = {};
	for (var i = 0; i < keys.length; i++) {
		var key = keys[i];
    	sorted[key] = obj[key];
	}
	return sorted;
}

Solution 7 - Javascript

This should be used with caution as your code shouldn't rely on Object properties order. If it's just a matter of presentation (or just for the fun !), you can sort properties deeply like this :

function sortObject(src) {
  var out;
  if (typeof src === 'object' && Object.keys(src).length > 0) {
    out = {};
    Object.keys(src).sort().forEach(function (key) {
      out[key] = sortObject(src[key]);
    });
    return out;
  }
  return src;
}

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
Questionmatto1990View Question on Stackoverflow
Solution 1 - JavascriptChris NielsenView Answer on Stackoverflow
Solution 2 - JavascriptBretonView Answer on Stackoverflow
Solution 3 - JavascriptexebookView Answer on Stackoverflow
Solution 4 - JavascriptJohn WilliamsView Answer on Stackoverflow
Solution 5 - Javascriptsteven7mwesigwaView Answer on Stackoverflow
Solution 6 - JavascriptsplashoutView Answer on Stackoverflow
Solution 7 - JavascriptPierre MaouiView Answer on Stackoverflow