Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a JavaScript object by property name

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?

like image 502
matto1990 Avatar asked Aug 31 '09 22:08

matto1990


People also ask

Can you sort objects JavaScript?

To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.

Does order of properties in object matter in JavaScript?

YES (but not always insertion order). Most Browsers iterate object properties as: Integer keys in ascending order (and strings like "1" that parse as ints) String keys, in insertion order (ES2015 guarantees this and all browsers comply) Symbol names, in insertion order (ES2015 guarantees this and all browsers comply)

How do you sort names in JavaScript?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


1 Answers

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; } 
like image 126
Chris Nielsen Avatar answered Sep 23 '22 21:09

Chris Nielsen