Home >Web Front-end >JS Tutorial >How to Sort a JavaScript Object's Keys Alphabetically?

How to Sort a JavaScript Object's Keys Alphabetically?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 03:29:17708browse

How to Sort a JavaScript Object's Keys Alphabetically?

How to Sort JavaScript Objects by Key

If you have a JavaScript object, you may want to reorganize its properties alphabetically for improved readability or processing purposes. This can be achieved by utilizing the following steps:


  • Extract the object's keys into an array using
    Object.keys(...)
    .
  • Sort the array of keys alphabetically using
    .sort()
    .
  • Create a new object to hold the sorted properties. Iterate through the sorted keys array and add each key along with its corresponding value from the original object to the new object using a reducer function.

The following code demonstrates the process:

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"}'

After executing these steps, your object will be sorted by its keys alphabetically.

The above is the detailed content of How to Sort a JavaScript Object's Keys Alphabetically?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn