Javascript: Sorting object by keys


Method 1: ES6

function sort_obj_by_keys(obj) {
  return Object.keys(obj).
  	sort().
    reduce((r, v) => ({ ...r, [v]: obj[v] }), {});  
}

var obj = {
  a: 300,
  c: 60,
  b: 200,
  f: 1000,
  d: 400,
  e: 8 * 60 * 60
};

console.log(JSON.stringify(sort_obj_by_keys(obj)))
//{"a":300,"b":200,"c":60,"d":400,"e":28800,"f":1000}

Method 2: ES5

function sort_obj_by_keys(obj) {
  return Object.keys(obj).
  	sort().
    reduce((a, v) => {
    	a[v] = obj[v];
    	return a; 
    }, {}); 
}

Method 3: ES3

function sort_obj_by_keys(obj) {
  var sortable = [];
  for (var i in obj) {
    sortable.push([i, obj[i]]);
  }
  sortable.sort(function(a, b) {
    return a[0] > b[0]? 1 : (a[0] < b[0]?-1:0);
  });
  var objSorted = {}
  sortable.forEach(function(item) {
    objSorted[item[0]] = item[1]
  })
  return objSorted
}

Method 4: ES8, use Object.entries() to convert the object into an array

function sort_obj_by_keys(obj) {
  return Object.entries(obj)
    .sort(([a,],[b,]) => a>b?1:(a<b?-1:0))
    .reduce((r, [k, v]) => ({ ...r, [k]: v }), {});  
}

Method 5: ES10, use Object.fromEntries() to convert array to object

function sort_obj_by_keys(obj) {
  return Object.fromEntries(
    Object.entries(obj).sort(([a,],[b,]) => a>b?1:(a<b?-1:0))
  );  
}

Leave a Reply