Languages
[Edit]
EN

JavaScript - get object properties sorted by key

3 points
Created by:
Violetd
835

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

Note:

Object properties are ordered since ES6.

 

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.

See also

  1. JavaScript - get object properties sorted by value (ES8+)

References

Alternative titles

  1. JavaScript - sorting object by property name
  2. JavaScript - sort object by key
  3. JavaScript - sorting object by key
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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