Sort JavaScript Object Keys

Introduction

Today we're going to how you can sort keys/properties in JavaScript objects. This is a bit of a gray area in JS since object keys have no inherent order like array items do, but that doesn't mean it isn't possible.

JavaScript Objects

In JavaScript, an object is an entity with properties and values. It's like a storage box that you can put different types of items into. Each item in the box is accessed via a unique key. Here's a simple example of an object:

let student = {
    name: "John Doe",
    age: 20,
    grade: "A"
};

In this object, name, age, and grade are the keys (also known as properties), and "John Doe", 20, and "A" are their corresponding values.

Note: Keys in JavaScript objects are always strings, even if you don't explicitly quote them. So, age is the same as "age".

Why Sort JavaScript Object Keys/Properties?

There might be situations where you need to sort the keys of a JavaScript object. For instance, you might be dealing with an object with a large number of keys and you need to present them in a sorted, readable format. Or perhaps you're writing unit tests, and you need a consistent order of keys to make your tests more predictable. It's not necessarily considered good practice, but there are still reasons why many programmers want to do it.

How to Sort Object Keys/Properties

JavaScript doesn't provide a built-in way to sort object keys. But don't worry, we can achieve this with a little bit of creativity.

Here's a function that takes an object and returns a new object with sorted keys:

function sortObjectKeys(obj) {
    return Object.keys(obj).sort().reduce((result, key) => {
        console.log(key);
        result[key] = obj[key];
        return result;
    }, {});
}

let student = {
    name: "John Doe",
    age: 20,
    grade: "A"
};

console.log(sortObjectKeys(student));

When you run this code, you'll get:

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

{
    age: 20,
    grade: "A",
    name: "John Doe"
}

As you can see, the keys are sorted in ascending order.

This works by first getting an array of the object's keys using Object.keys(), then sorting that array using Array.prototype.sort(). It then uses Array.prototype.reduce() to build a new object with the sorted keys. The keys are then shown in the order in which they were inserted into the new object.

ES6 Sort Order of Object Keys/Properties

It is widely believed that object properties have no order, and therefore you can't rely on any ordering that the properties seem to have. While this is true, as we have shown above, ordering is possible, to an extent.

According to Exploring ES6, properties are returned in the following order:

  1. Array indices, in order
  2. String keys in the order in which they were added to the property
  3. Symbols in the order in which they were added to the property

The majority (but not all!) of objects use only string keys. However, if you also use array indices or symbols as properties, you'll no longer be able iterate over them in the order in which they were added to the object.

Conclusion

This Byte explained how to sort JavaScript object keys/properties. We learned that while object keys aren't inherently ordered, there is some ordering to them, which you can take advantage of. Understanding these nuances of JavaScript can help you not only improve the effectiveness of your code, but the quality and robustness as well.

Last Updated: September 19th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms