Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort JavaScript object by key

I need to sort JavaScript objects by key.

Hence the following:

{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' } 

Would become:

{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' } 
like image 512
vdh_ant Avatar asked Mar 29 '11 02:03

vdh_ant


People also ask

Can you sort an object keys in 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.

How do I sort a JSON key?

Enter your JSON into the first text area, or drag and drop a file, after, select the sort method you're going to use, key value requires the key name (if not specified selects the first key), click the example button to get an idea on how it works. The result will automatically sort and display in the output text area.

How do I sort objects in typescript?

Array. sort() function sorts an Array. The Sort() function will sort array using the optional compareFunction provided, if it is not provided Javascript will sort the array object by converting values to strings and comparing strings in UTF-16 code units order.


1 Answers

The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6 / ES2015 spec has been published.


See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:

All methods that iterate over property keys do so in the same order:

  1. First all Array indices, sorted numerically.
  2. Then all string keys (that are not indices), in the order in which they were created.
  3. Then all symbols, in the order in which they were created.

So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.

Here’s how you can sort an object by its keys/properties, alphabetically:

const unordered = {   'b': 'foo',   'c': 'bar',   'a': 'baz' };  console.log(JSON.stringify(unordered)); // → '{"b":"foo","c":"bar","a":"baz"}'  const ordered = Object.keys(unordered).sort().reduce(   (obj, key) => {      obj[key] = unordered[key];      return obj;   },    {} );  console.log(JSON.stringify(ordered)); // → '{"a":"baz","b":"foo","c":"bar"}'

Use var instead of const for compatibility with ES5 engines.

like image 77
Mathias Bynens Avatar answered Sep 29 '22 02:09

Mathias Bynens