[javascript] Sort JavaScript object by key

I need to sort JavaScript objects by key.

Hence the following:

{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }

Would become:

{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }

This question is related to javascript sorting

The answer is


The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6 / ES2015 spec has been published.


See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:

All methods that iterate over property keys do so in the same order:

  1. First all Array indices, sorted numerically.
  2. Then all string keys (that are not indices), in the order in which they were created.
  3. Then all symbols, in the order in which they were created.

So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.

Here’s how you can sort an object by its keys/properties, alphabetically:

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

Use var instead of const for compatibility with ES5 engines.


This is an old question, but taking the cue from Mathias Bynens' answer, I've made a short version to sort the current object, without much overhead.

    Object.keys(unordered).sort().forEach(function(key) {
        var value = unordered[key];
        delete unordered[key];
        unordered[key] = value;
    });

after the code execution, the "unordered" object itself will have the keys alphabetically sorted.


The one line:

Object.entries(unordered)
  .sort(([keyA], [keyB]) => keyA > keyB)
  .reduce((obj, [key,value]) => Object.assign(obj, {[key]: value}), {})

It's 2019 and we have a 2019 way to solve this :)

Object.fromEntries(Object.entries({b: 3, a:8, c:1}).sort())

Here is a one line solution (not the most efficient but when it comes to thin objects like in your example I'd rather use native JS functions then messing up with sloppy loops)

_x000D_
_x000D_
const unordered = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }

const ordered = Object.fromEntries(Object.entries(unordered).sort())

console.log(ordered); // a->b->c
_x000D_
_x000D_
_x000D_


I transfered some Java enums to javascript objects.

These objects returned correct arrays for me. if object keys are mixed type (string, int, char), there is a problem.

_x000D_
_x000D_
var Helper = {_x000D_
    isEmpty: function (obj) {_x000D_
        return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;_x000D_
    },_x000D_
_x000D_
    isObject: function (obj) {_x000D_
        return (typeof obj === 'object');_x000D_
    },_x000D_
_x000D_
    sortObjectKeys: function (object) {_x000D_
        return Object.keys(object)_x000D_
            .sort(function (a, b) {_x000D_
                c = a - b;_x000D_
                return c_x000D_
            });_x000D_
    },_x000D_
    containsItem: function (arr, item) {_x000D_
        if (arr && Array.isArray(arr)) {_x000D_
            return arr.indexOf(item) > -1;_x000D_
        } else {_x000D_
            return arr === item;_x000D_
        }_x000D_
    },_x000D_
_x000D_
    pushArray: function (arr1, arr2) {_x000D_
        if (arr1 && arr2 && Array.isArray(arr1)) {_x000D_
            arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);_x000D_
        }_x000D_
    }_x000D_
};_x000D_
_x000D_
function TypeHelper() {_x000D_
    var _types = arguments[0],_x000D_
        _defTypeIndex = 0,_x000D_
        _currentType,_x000D_
        _value;_x000D_
_x000D_
    if (arguments.length == 2) {_x000D_
        _defTypeIndex = arguments[1];_x000D_
    }_x000D_
_x000D_
    Object.defineProperties(this, {_x000D_
        Key: {_x000D_
            get: function () {_x000D_
                return _currentType;_x000D_
            },_x000D_
            set: function (val) {_x000D_
                _currentType.setType(val, true);_x000D_
            },_x000D_
            enumerable: true_x000D_
        },_x000D_
        Value: {_x000D_
            get: function () {_x000D_
                return _types[_currentType];_x000D_
            },_x000D_
            set: function (val) {_x000D_
                _value.setType(val, false);_x000D_
            },_x000D_
            enumerable: true_x000D_
        }_x000D_
    });_x000D_
_x000D_
    this.getAsList = function (keys) {_x000D_
        var list = [];_x000D_
        Helper.sortObjectKeys(_types).forEach(function (key, idx, array) {_x000D_
            if (key && _types[key]) {_x000D_
_x000D_
                if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {_x000D_
                    var json = {};_x000D_
                    json.Key = key;_x000D_
                    json.Value = _types[key];_x000D_
                    Helper.pushArray(list, json);_x000D_
                }_x000D_
            }_x000D_
        });_x000D_
        return list;_x000D_
    };_x000D_
_x000D_
    this.setType = function (value, isKey) {_x000D_
        if (!Helper.isEmpty(value)) {_x000D_
            Object.keys(_types).forEach(function (key, idx, array) {_x000D_
                if (Helper.isObject(value)) {_x000D_
                    if (value && value.Key == key) {_x000D_
                        _currentType = key;_x000D_
                    }_x000D_
                } else if (isKey) {_x000D_
                    if (value && value.toString() == key.toString()) {_x000D_
                        _currentType = key;_x000D_
                    }_x000D_
                } else if (value && value.toString() == _types[key]) {_x000D_
                    _currentType = key;_x000D_
                }_x000D_
            });_x000D_
        } else {_x000D_
            this.setDefaultType();_x000D_
        }_x000D_
        return isKey ? _types[_currentType] : _currentType;_x000D_
    };_x000D_
_x000D_
    this.setTypeByIndex = function (index) {_x000D_
        var keys = Helper.sortObjectKeys(_types);_x000D_
        for (var i = 0; i < keys.length; i++) {_x000D_
            if (index === i) {_x000D_
                _currentType = keys[index];_x000D_
                break;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
_x000D_
    this.setDefaultType = function () {_x000D_
        this.setTypeByIndex(_defTypeIndex);_x000D_
    };_x000D_
_x000D_
    this.setDefaultType();_x000D_
}_x000D_
_x000D_
_x000D_
var TypeA = {_x000D_
    "-1": "Any",_x000D_
    "2": "2L",_x000D_
    "100": "100L",_x000D_
    "200": "200L",_x000D_
    "1000": "1000L"_x000D_
};_x000D_
_x000D_
var TypeB = {_x000D_
    "U": "Any",_x000D_
    "W": "1L",_x000D_
    "V": "2L",_x000D_
    "A": "100L",_x000D_
    "Z": "200L",_x000D_
    "K": "1000L"_x000D_
};_x000D_
console.log('keys of TypeA', Helper.sortObjectKeys(TypeA));//keys of TypeA ["-1", "2", "100", "200", "1000"]_x000D_
_x000D_
console.log('keys of TypeB', Helper.sortObjectKeys(TypeB));//keys of TypeB ["U", "W", "V", "A", "Z", "K"]_x000D_
_x000D_
var objectTypeA = new TypeHelper(TypeA),_x000D_
    objectTypeB = new TypeHelper(TypeB);_x000D_
_x000D_
console.log('list of objectA = ', objectTypeA.getAsList());_x000D_
console.log('list of objectB = ', objectTypeB.getAsList());
_x000D_
_x000D_
_x000D_

Types:

var TypeA = {
    "-1": "Any",
    "2": "2L",
    "100": "100L",
    "200": "200L",
    "1000": "1000L"
};

var TypeB = {
    "U": "Any",
    "W": "1L",
    "V": "2L",
    "A": "100L",
    "Z": "200L",
    "K": "1000L"
};


Sorted Keys(output):

Key list of TypeA -> ["-1", "2", "100", "200", "1000"]

Key list of TypeB -> ["U", "W", "V", "A", "Z", "K"]

Object.keys(unordered).sort().reduce(
    (acc,curr) => ({...acc, [curr]:unordered[curr]})
    , {}
)

A lot of people have mention that "objects cannot be sorted", but after that they are giving you a solution which works. Paradox, isn't it?

No one mention why those solutions are working. They are, because in most of the browser's implementations values in objects are stored in the order in which they were added. That's why if you create new object from sorted list of keys it's returning an expected result.

And I think that we could add one more solution – ES5 functional way:

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

ES2015 version of above (formatted to "one-liner"):

const sortObject = o => Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {})

Short explanation of above examples (as asked in comments):

Object.keys is giving us a list of keys in provided object (obj or o), then we're sorting those using default sorting algorithm, next .reduce is used to convert that array back into an object, but this time with all of the keys sorted.


Pure JavaScript answer to sort an Object. This is the only answer that I know of that will handle negative numbers. This function is for sorting numerical Objects.

Input obj = {1000: {}, -1200: {}, 10000: {}, 200: {}};

function osort(obj) {
var keys = Object.keys(obj);
var len = keys.length;
var rObj = [];
var rK = [];
var t = Object.keys(obj).length;
while(t > rK.length) {
    var l = null;
    for(var x in keys) {
        if(l && parseInt(keys[x]) < parseInt(l)) {
            l = keys[x];
            k = x;
        }
        if(!l) { // Find Lowest
            var l = keys[x];
            var k = x;
        }
    }
    delete keys[k];
    rK.push(l);
}

for (var i = 0; i < len; i++) {

    k = rK[i];
    rObj.push(obj[k]);
}
return rObj;
}

The output will be an object sorted by those numbers with new keys starting at 0.


Underscore version:

function order(unordered)
{
return _.object(_.sortBy(_.pairs(unordered),function(o){return o[0]}));
}

If you don't trust your browser for keeping the order of the keys, I strongly suggest to rely on a ordered array of key-value paired arrays.

_.sortBy(_.pairs(c),function(o){return o[0]})

Using lodash this will work:

some_map = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }

// perform a function in order of ascending key
_(some_map).keys().sort().each(function (key) {
  var value = some_map[key];
  // do something
});

// or alternatively to build a sorted list
sorted_list = _(some_map).keys().sort().map(function (key) {
  var value = some_map[key];
  // return something that shall become an item in the sorted list
}).value();

Just food for thought.


function sortObjectKeys(obj){
    return Object.keys(obj).sort().reduce((acc,key)=>{
        acc[key]=obj[key];
        return acc;
    },{});
}

sortObjectKeys({
    telephone: '069911234124',
    name: 'Lola',
    access: true,
});

This works for me

/**
 * Return an Object sorted by it's Key
 */
var sortObjectByKey = function(obj){
    var keys = [];
    var sorted_obj = {};

    for(var key in obj){
        if(obj.hasOwnProperty(key)){
            keys.push(key);
        }
    }

    // sort keys
    keys.sort();

    // create new array based on Sorted Keys
    jQuery.each(keys, function(i, key){
        sorted_obj[key] = obj[key];
    });

    return sorted_obj;
};

As already mentioned, objects are unordered.

However...

You may find this idiom useful:

var o = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' };

var kv = [];

for (var k in o) {
  kv.push([k, o[k]]);
}

kv.sort()

You can then iterate through kv and do whatever you wish.

> kv.sort()
[ [ 'a', 'dsfdsfsdf' ],
  [ 'b', 'asdsad' ],
  [ 'c', 'masdas' ] ]

Just to simplify it and make it more clear the answer from Matt Ball

_x000D_
_x000D_
//your object_x000D_
var myObj = {_x000D_
    b : 'asdsadfd',_x000D_
    c : 'masdasaf',_x000D_
    a : 'dsfdsfsdf'_x000D_
  };_x000D_
_x000D_
//fixed code_x000D_
var keys = [];_x000D_
for (var k in myObj) {_x000D_
  if (myObj.hasOwnProperty(k)) {_x000D_
    keys.push(k);_x000D_
  }_x000D_
}_x000D_
keys.sort();_x000D_
for (var i = 0; i < keys.length; i++) {_x000D_
  k = keys[i];_x000D_
  alert(k + ':' + myObj[k]);_x000D_
}
_x000D_
_x000D_
_x000D_


recursive sort, for nested object and arrays

function sortObjectKeys(obj){
    return Object.keys(obj).sort().reduce((acc,key)=>{
        if (Array.isArray(obj[key])){
            acc[key]=obj[key].map(sortObjectKeys);
        }
        if (typeof obj[key] === 'object'){
            acc[key]=sortObjectKeys(obj[key]);
        }
        else{
            acc[key]=obj[key];
        }
        return acc;
    },{});
}

// test it
sortObjectKeys({
    telephone: '069911234124',
    name: 'Lola',
    access: true,
    cars: [
        {name: 'Family', brand: 'Volvo', cc:1600},
        {
            name: 'City', brand: 'VW', cc:1200, 
            interior: {
                wheel: 'plastic',
                radio: 'blaupunkt'
            }
        },
        {
            cc:2600, name: 'Killer', brand: 'Plymouth',
            interior: {
                wheel: 'wooden',
                radio: 'earache!'
            }
        },
    ]
});

ES6 - here is the 1 liner

_x000D_
_x000D_
var data = { zIndex:99,
             name:'sravan',
             age:25, 
             position:'architect',
             amount:'100k',
             manager:'mammu' };

console.log(Object.entries(data).sort().reduce( (o,[k,v]) => (o[k]=v,o), {} ));
_x000D_
_x000D_
_x000D_


JavaScript objects1 are not ordered. It is meaningless to try to "sort" them. If you want to iterate over an object's properties, you can sort the keys and then retrieve the associated values:

_x000D_
_x000D_
var myObj = {_x000D_
    'b': 'asdsadfd',_x000D_
    'c': 'masdasaf',_x000D_
    'a': 'dsfdsfsdf'_x000D_
  },_x000D_
  keys = [],_x000D_
  k, i, len;_x000D_
_x000D_
for (k in myObj) {_x000D_
  if (myObj.hasOwnProperty(k)) {_x000D_
    keys.push(k);_x000D_
  }_x000D_
}_x000D_
_x000D_
keys.sort();_x000D_
_x000D_
len = keys.length;_x000D_
_x000D_
for (i = 0; i < len; i++) {_x000D_
  k = keys[i];_x000D_
  console.log(k + ':' + myObj[k]);_x000D_
}
_x000D_
_x000D_
_x000D_


Alternate implementation using Object.keys fanciness:

_x000D_
_x000D_
var myObj = {_x000D_
    'b': 'asdsadfd',_x000D_
    'c': 'masdasaf',_x000D_
    'a': 'dsfdsfsdf'_x000D_
  },_x000D_
  keys = Object.keys(myObj),_x000D_
  i, len = keys.length;_x000D_
_x000D_
keys.sort();_x000D_
_x000D_
for (i = 0; i < len; i++) {_x000D_
  k = keys[i];_x000D_
  console.log(k + ':' + myObj[k]);_x000D_
}
_x000D_
_x000D_
_x000D_


1Not to be pedantic, but there's no such thing as a JSON object.


There's a great project by @sindresorhus called sort-keys that works awesome.

You can check its source code here:

https://github.com/sindresorhus/sort-keys

Or you can use it with npm:

$ npm install --save sort-keys

Here are also code examples from his readme

const sortKeys = require('sort-keys');

sortKeys({c: 0, a: 0, b: 0});
//=> {a: 0, b: 0, c: 0}

sortKeys({b: {b: 0, a: 0}, a: 0}, {deep: true});
//=> {a: 0, b: {a: 0, b: 0}}

sortKeys({c: 0, a: 0, b: 0}, {
    compare: (a, b) => -a.localeCompare(b)
});
//=> {c: 0, b: 0, a: 0}

Guys I'm figuratively shocked! Sure all answers are somewhat old, but no one did even mention the stability in sorting! So bear with me I'll try my best to answer the question itself and go into details here. So I'm going to apologize now it will be a lot to read.

Since it is 2018 I will only use ES6, the Polyfills are all available at the MDN docs, which I will link at the given part.


Answer to the question:

If your keys are only numbers then you can safely use Object.keys() together with Array.prototype.reduce() to return the sorted object:

// Only numbers to show it will be sorted.
const testObj = {
  '2000': 'Articel1',
  '4000': 'Articel2',
  '1000': 'Articel3',
  '3000': 'Articel4',
};

// I'll explain what reduces does after the answer.
console.log(Object.keys(testObj).reduce((accumulator, currentValue) => {
  accumulator[currentValue] = testObj[currentValue];
  return accumulator;
}, {}));

/**
 * expected output:
 * {
 * '1000': 'Articel3',
 * '2000': 'Articel1',
 * '3000': 'Articel4',
 * '4000': 'Articel2' 
 *  } 
 */

// if needed here is the one liner:
console.log(Object.keys(testObj).reduce((a, c) => (a[c] = testObj[c], a), {}));

However if you are working with strings I highly recommend chaining Array.prototype.sort() into all of this:

// String example
const testObj = {
  'a1d78eg8fdg387fg38': 'Articel1',
  'z12989dh89h31d9h39': 'Articel2',
  'f1203391dhj32189h2': 'Articel3',
  'b10939hd83f9032003': 'Articel4',
};
// Chained sort into all of this.
console.log(Object.keys(testObj).sort().reduce((accumulator, currentValue) => {
  accumulator[currentValue] = testObj[currentValue];
  return accumulator;
}, {}));

/**
 * expected output:   
 * { 
 * a1d78eg8fdg387fg38: 'Articel1',
 * b10939hd83f9032003: 'Articel4',
 * f1203391dhj32189h2: 'Articel3',
 * z12989dh89h31d9h39: 'Articel2' 
 * }
 */

// again the one liner:
console.log(Object.keys(testObj).sort().reduce((a, c) => (a[c] = testObj[c], a), {}));

If someone is wondering what reduce does:

// Will return Keys of object as an array (sorted if only numbers or single strings like a,b,c).
Object.keys(testObj)

// Chaining reduce to the returned array from Object.keys().
// Array.prototype.reduce() takes one callback 
// (and another param look at the last line) and passes 4 arguments to it: 
// accumulator, currentValue, currentIndex and array
.reduce((accumulator, currentValue) => {

  // setting the accumulator (sorted new object) with the actual property from old (unsorted) object.
  accumulator[currentValue] = testObj[currentValue];

  // returning the newly sorted object for the next element in array.
  return accumulator;

  // the empty object {} ist the initial value for  Array.prototype.reduce().
}, {});

If needed here is the explanation for the one liner:

Object.keys(testObj).reduce(

  // Arrow function as callback parameter.
  (a, c) => 

  // parenthesis return! so we can safe the return and write only (..., a);
  (a[c] = testObj[c], a)

  // initial value for reduce.
  ,{}
);

Why Sorting is a bit complicated:

In short Object.keys() will return an array with the same order as we get with a normal loop:

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

Sidenote - you can use Object.keys() on arrays as well, keep in mind the index will be returned:

// simple array
const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

But it is not as easy as shown by those examples, real world objects may contain numbers and alphabetical characters or even symbols (please don't do it).

Here is an example with all of them in one object:

// This is just to show what happens, please don't use symbols in keys.
const testObj = {
  '1asc': '4444',
  1000: 'a',
  b: '1231',
  '#01010101010': 'asd',
  2: 'c'
};

console.log(Object.keys(testObj));
// output: [ '2', '1000', '1asc', 'b', '#01010101010' ]

Now if we use Array.prototype.sort() on the array above the output changes:

console.log(Object.keys(testObj).sort());
// output: [ '#01010101010', '1000', '1asc', '2', 'b' ]

Here is a quote from the docs:

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

The time and space complexity of the sort cannot be guaranteed as it is implementation dependent.

You have to make sure that one of them returns the desired output for you. In reallife examples people tend to mix up things expecially if you use different information inputs like APIs and Databases together.


So what's the big deal?

Well there are two articles which every programmer should understand:

In-place algorithm:

In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. In-place algorithm updates input sequence only through replacement or swapping of elements. An algorithm which is not in-place is sometimes called not-in-place or out-of-place.

So basically our old array will be overwritten! This is important if you want to keep the old array for other reasons. So keep this in mind.

Sorting algorithm

Stable sort algorithms sort identical elements in the same order that they appear in the input. When sorting some kinds of data, only part of the data is examined when determining the sort order. For example, in the card sorting example to the right, the cards are being sorted by their rank, and their suit is being ignored. This allows the possibility of multiple different correctly sorted versions of the original list. Stable sorting algorithms choose one of these, according to the following rule: if two items compare as equal, like the two 5 cards, then their relative order will be preserved, so that if one came before the other in the input, it will also come before the other in the output.

enter image description here

An example of stable sort on playing cards. When the cards are sorted by rank with a stable sort, the two 5s must remain in the same order in the sorted output that they were originally in. When they are sorted with a non-stable sort, the 5s may end up in the opposite order in the sorted output.

This shows that the sorting is right but it changed. So in the real world even if the sorting is correct we have to make sure that we get what we expect! This is super important keep this in mind as well. For more JavaScript examples look into the Array.prototype.sort() - docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


Here is a clean lodash-based version that works with nested objects

/**
 * Sort of the keys of an object alphabetically
 */
const sortKeys = function(obj) {
  if(_.isArray(obj)) {
    return obj.map(sortKeys);
  }
  if(_.isObject(obj)) {
    return _.fromPairs(_.keys(obj).sort().map(key => [key, sortKeys(obj[key])]));
  }
  return obj;
};

It would be even cleaner if lodash had a toObject() method...


the best way to do it is

 const object =  Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {})

 //else if its in reverse just do 

 const object = Object.keys(0).reverse ()

You can first convert your almost-array-like object to a real array, and then use .reverse():

Object.assign([], {1:'banana', 2:'apple', 
3:'orange'}).reverse();
// [ "orange", "apple", "banana", <1 empty slot> ]

The empty slot at the end if cause because your first index is 1 instead of 0. You can remove the empty slot with .length-- or .pop().

Alternatively, if you want to borrow .reverse and call it on the same object, it must be a fully-array-like object. That is, it needs a length property:

Array.prototype.reverse.call({1:'banana', 2:'apple', 
3:'orange', length:4});
// {0:"orange", 1:"apple", 3:"banana", length:4}

Note it will return the same fully-array-like object object, so it won't be a real array. You can then use delete to remove the length property.


Maybe a bit more elegant form:

_x000D_
_x000D_
 /**_x000D_
     * Sorts a key-value object by key, maintaining key to data correlations._x000D_
     * @param {Object} src  key-value object_x000D_
     * @returns {Object}_x000D_
     */_x000D_
var ksort = function ( src ) {_x000D_
      var keys = Object.keys( src ),_x000D_
          target = {};_x000D_
      keys.sort();_x000D_
      keys.forEach(function ( key ) {_x000D_
        target[ key ] = src[ key ];_x000D_
      });_x000D_
      return target;_x000D_
    };_x000D_
_x000D_
_x000D_
// Usage_x000D_
console.log(ksort({_x000D_
  a:1,_x000D_
  c:3,_x000D_
  b:2  _x000D_
}));
_x000D_
_x000D_
_x000D_

P.S. and the same with ES6+ syntax:

function ksort( src ) {
  const keys = Object.keys( src );
  keys.sort();
  return keys.reduce(( target, key ) => {
        target[ key ] = src[ key ];
        return target;
  }, {});
};

Suppose it could be useful in VisualStudio debugger which shows unordered object properties.

(function(s) {
    var t = {};

    Object.keys(s).sort().forEach(function(k) {
        t[k] = s[k]
    });

    return t
})({
    b: 2,
    a: 1,
    c: 3
});

Simple and readable snippet, using lodash.

You need to put the key in quotes only when calling sortBy. It doesn't have to be in quotes in the data itself.

_.sortBy(myObj, "key")

Also, your second parameter to map is wrong. It should be a function, but using pluck is easier.

_.map( _.sortBy(myObj, "key") , "value");

Just use lodash to unzip map and sortBy first value of pair and zip again it will return sorted key.

If you want sortby value change pair index to 1 instead of 0

var o = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' };
console.log(_(o).toPairs().sortBy(0).fromPairs().value())

enter image description here


Solution:

function getSortedObject(object) {
  var sortedObject = {};

  var keys = Object.keys(object);
  keys.sort();

  for (var i = 0, size = keys.length; i < size; i++) {
    key = keys[i];
    value = object[key];
    sortedObject[key] = value;
  }

  return sortedObject;
}

// Test run
getSortedObject({d: 4, a: 1, b: 2, c: 3});

Explanation:

Many JavaScript runtimes store values inside an object in the order in which they are added.

To sort the properties of an object by their keys you can make use of the Object.keys function which will return an array of keys. The array of keys can then be sorted by the Array.prototype.sort() method which sorts the elements of an array in place (no need to assign them to a new variable).

Once the keys are sorted you can start using them one-by-one to access the contents of the old object to fill a new object (which is now sorted).

Below is an example of the procedure (you can test it in your targeted browsers):

_x000D_
_x000D_
/**_x000D_
 * Returns a copy of an object, which is ordered by the keys of the original object._x000D_
 *_x000D_
 * @param {Object} object - The original object._x000D_
 * @returns {Object} Copy of the original object sorted by keys._x000D_
 */_x000D_
function getSortedObject(object) {_x000D_
  // New object which will be returned with sorted keys_x000D_
  var sortedObject = {};_x000D_
_x000D_
  // Get array of keys from the old/current object_x000D_
  var keys = Object.keys(object);_x000D_
  // Sort keys (in place)_x000D_
  keys.sort();_x000D_
_x000D_
  // Use sorted keys to copy values from old object to the new one_x000D_
  for (var i = 0, size = keys.length; i < size; i++) {_x000D_
    key = keys[i];_x000D_
    value = object[key];_x000D_
    sortedObject[key] = value;_x000D_
  }_x000D_
_x000D_
  // Return the new object_x000D_
  return sortedObject;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Test run_x000D_
 */_x000D_
var unsortedObject = {_x000D_
  d: 4,_x000D_
  a: 1,_x000D_
  b: 2,_x000D_
  c: 3_x000D_
};_x000D_
_x000D_
var sortedObject = getSortedObject(unsortedObject);_x000D_
_x000D_
for (var key in sortedObject) {_x000D_
  var text = "Key: " + key + ", Value: " + sortedObject[key];_x000D_
  var paragraph = document.createElement('p');_x000D_
  paragraph.textContent = text;_x000D_
  document.body.appendChild(paragraph);_x000D_
}
_x000D_
_x000D_
_x000D_

Note: Object.keys is an ECMAScript 5.1 method but here is a polyfill for older browsers:

if (!Object.keys) {
  Object.keys = function (object) {
    var key = [];
    var property = undefined;
    for (property in object) {
      if (Object.prototype.hasOwnProperty.call(object, property)) {
        key.push(property);
      }
    }
    return key;
  };
}

Sorts keys recursively while preserving references.

function sortKeys(o){
    if(o && o.constructor === Array)
        o.forEach(i=>sortKeys(i));
    else if(o && o.constructor === Object)
        Object.entries(o).sort((a,b)=>a[0]>b[0]?1:-1).forEach(e=>{
            sortKeys(e[1]);
            delete o[e[0]];
            o[e[0]] = e[1];
        });
}

Example:

let x = {d:3, c:{g:20, a:[3,2,{s:200, a:100}]}, a:1};
let y = x.c;
let z = x.c.a[2];
sortKeys(x);
console.log(x); // {a: 1, c: {a: [3, 2, {a: 1, s: 2}], g: 2}, d: 3}
console.log(y); // {a: [3, 2, {a: 100, s: 200}}, g: 20}
console.log(z); // {a: 100, s: 200}

Use this code if you have nested objects or if you have nested array obj.

var sortObjectByKey = function(obj){
    var keys = [];
    var sorted_obj = {};
    for(var key in obj){
        if(obj.hasOwnProperty(key)){
            keys.push(key);
        }
    }
    // sort keys
    keys.sort();

    // create new array based on Sorted Keys
    jQuery.each(keys, function(i, key){
        var val = obj[key];
        if(val instanceof Array){
            //do for loop;
            var arr = [];
            jQuery.each(val,function(){
                arr.push(sortObjectByKey(this));
            }); 
            val = arr;

        }else if(val instanceof Object){
            val = sortObjectByKey(val)
        }
        sorted_obj[key] = val;
    });
    return sorted_obj;
};

This is a lightweight solution to everything I need for JSON sorting.

function sortObj(obj) {
    if (typeof obj !== "object" || obj === null)
        return obj;

    if (Array.isArray(obj))
        return obj.map((e) => sortObj(e)).sort();

    return Object.keys(obj).sort().reduce((sorted, k) => {
        sorted[k] = sortObj(obj[k]);
        return sorted;
    }, {});
}

Not sure if this answers the question, but this is what I needed.

Maps.iterate.sorted = function (o, callback) {
    var keys = Object.keys(o), sorted = keys.sort(), k; 
    if ( callback ) {
            var i = -1;
            while( ++i < sorted.length ) {
                    callback(k = sorted[i], o[k] );
            }
    }

    return sorted;
}

Called as :

Maps.iterate.sorted({c:1, b:2, a:100}, function(k, v) { ... } ) 

I am actually very surprised that over 30 answers were given, and yet none gave a full deep solution for this problem. Some had shallow solution, while others had deep but faulty (it'll crash if undefined, function or symbol will be in the json).

Here is the full solution:

function sortObject(unordered, sortArrays = false) {
  if (!unordered || typeof unordered !== 'object') {
    return unordered;
  }

  if (Array.isArray(unordered)) {
    const newArr = unordered.map((item) => sortObject(item, sortArrays));
    if (sortArrays) {
      newArr.sort();
    }
    return newArr;
  }

  const ordered = {};
  Object.keys(unordered)
    .sort()
    .forEach((key) => {
      ordered[key] = sortObject(unordered[key], sortArrays);
    });
  return ordered;
}

const json = {
  b: 5,
  a: [2, 1],
  d: {
    b: undefined,
    a: null,
    c: false,
    d: true,
    g: '1',
    f: [],
    h: {},
    i: 1n,
    j: () => {},
    k: Symbol('a')
  },
  c: [
    {
      b: 1,
      a: 1
    }
  ]
};
console.log(sortObject(json, true));