Languages
[Edit]
EN

JavaScript - get object properties sorted by key

3 points
Created by:
Dirask Community
6900

In this article, we would like to show you how to get object properties sorted by key in JavaScript.

The main concept of this solution is to use:

  • keys() method which returns an array of given object property names,
  • sort() method to sort the array,
  • reduce() method to create a new object from the array with sorted properties.

Runnable example:

// ONLINE-RUNNER:browser;

const object = {
  'b': 'bb',
  'c': 'cc',
  'a': 'aa'
};

const sortedObject = Object.keys(object)
  .sort()
  .reduce((result, key) => (result[key] = object[key], result),{});

console.log(JSON.stringify(object));       // {"b":"bb", "c":"cc", "a":"aa"}
console.log(JSON.stringify(sortedObject)); // {"a":"aa", "b":"bb", "c":"cc"}

Note:

The default sort order is ascending but elements converted into strings are compared by their sequences of UTF-16 code units values.

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join