Categories
JavaScript Answers

How to Sort or Order Keys in JavaScript Objects?

Spread the love

To sort or order keys in JavaScript objects, we can use the Object.keys method to get the keys of the object in a string array.

Then we call sort on the array to sort the string keys.

And then we use the reduce method to reconstruct the object with the sorted keys and return it.

For instance, we can write:

const notSorted = {
  b: false,
  a: true
}
const sorted = Object.keys(notSorted)
  .sort()
  .reduce((acc, key) => ({
    ...acc,
    [key]: notSorted[key]
  }), {})
console.log(sorted)

to sort the keys of the notSorted object by alphabetical order.

Then we call Object.keys with it to get the keys in a string array.

Next, we call sort in the returned array to sort the keys.

Then we call reduce with a callback to merge the items of the acc object which has the reconstructed so far.

And we put the key with the notSorted property value of the given key as its value.

In the 2nd argument, we pass in an empty object to initialize acc to an empty object.

Therefore, sorted is:

{a: true, b: false}

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.