JavaScript

Sort the Keys of an Object in JavaScript

Some developers prefer to set the object properties(key-value) names in alphabetical order. It helps to discover or compare necessary properties more quickly. More specifically, JavaScript provides some ways to get the object keys and then sort them in the desired order.

This blog post will describe the procedure for sorting the JavaScript object keys.

How to Sort the Keys of an Object in JavaScript?

To sort the object keys, use the “sort() method with the “Object.keys()” method. In this combination, the Object.keys() method gives the array of keys of the object in the same sequence as it is initialized, whereas the “sort()” method will sort all the keys in ascending order(alphabetically).

Syntax

Follow the given syntax for sorting the object keys in JavaScript:

Object.keys(obj).sort()

Example 1: Sort the Keys of an Object Using sort() Method

Create an object with key-value pairs:

var object = {

"JavaScript": 5,

"Java": 23,

"Python": 20,

"HTML": 7,

"CSS": 8

}

Call the sort() method with the Object.keys() method by passing the object as an argument:

var sortedKeys = Object.keys(object).sort();

Finally, print the sorted keys on the console:

console.log(sortedKeys);

The output displays the alphabetically sorted object keys:

Whereas the simple Object.keys() method returns the keys of the object:

var sortedKeys = Object.keys(object);

Output

If you want to get the entries (key-value pairs) of an object in a sorted form, follow the given section.

Example 2: Sort the Keys and Display the Corresponding Values of an Object Using reduce() Method

To sort the keys with values of an object, use the “reduce()” method with the “sort()” method. The sort() method returns the sorted array of keys of the object, and the reduce() method is used to iterate through the sorted object keys array and assign each key-value pair to an object:

var sortedKeys = Object.keys(object).sort().reduce((objEntries, key) => {

objEntries[key] = object[key];

return objEntries;

}, {});

The output shows the sorted keys with their values of an object:

We have gathered all the necessary information for sorting the object keys in JavaScript.

Conclusion

To sort the object keys, use the “sort()” method with the “Object.keys()” method. The Object.keys() method gives the array of keys of the object while the sort() method will sort all the keys in ascending order, and in terms of the alphabetic keys, it will sort in alphabetically. This tutorial described the procedure for sorting the object keys in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.