How to Sort JavaScript Object by Key

In this tutorial, we will share a very simple and functional method to sort an array of objects by key.

Here is a ES5 functional method of sorting. The Object.keys gives a list of keys in provided object, then you should sort those using default sorting algorithm, after which the reduce() method converts that array back into an object with all of the keys sorted:

function sortObj(obj) {
  return Object.keys(obj).sort().reduce(function (result, key) {
    result[key] = obj[key];
    return result;
  }, {});
}

Example:

function sortObj(obj) {
  return Object.keys(obj).sort().reduce(function (result, key) {
    result[key] = obj[key];
    return result;
  }, {});
}
let list = {
  "name": "Ann",
  "age": 75
};
let arr = sortObj(list);
console.log(arr);

A one-liner code piece of the above example:

const sortObject = obj => Object.keys(obj).sort().reduce((res, key) => (res[key] = obj[key], res), {})

Example:

const sortObject = obj => Object.keys(obj).sort().reduce((res, key) => (res[key] = obj[key], res), {});
let list = {
  "name": "John",
  "age": 20
};
let arr = sortObject(list);
console.log(arr);
This behaviour is available in all major browsers and has been standardized in ES6/ES2015.

Object.keys()

Object.keys() returns an array where elements are strings corresponding to the enumerable properties found upon the object. The order of the property is similar to that given by the object manually in a loop applied to the properties. Object.keys() is used to return enumerable properties of a simple array, of an array-like an object, and an array-like object with random ordering.

Do you find this helpful?

Related articles