There is a function:

sort: function (jsonData) { return jsonData.sort(function(a,b){ return (a < b.id) ? -1:1; }); }, 

Displays error: TypeError: jsonData.sort is not a function .
I understand that the sort function does not work with objects.
But I don’t understand how to return a sorted array (or object).

Example jsonData:

 Object{ 131:Object 132:Object 136:Object 139:Object 142:Object 143:Object 144:Object } 

I want a reverse sort.
This is not a duplicate. Re-sort json jquery result by a specific field , it is sorted by value, and I need by key. Moreover, the .sort function is shown there, and as I said, the function displays an error. I already wrote about this in the comments. Read fully before indicating that this is a duplicate!

  • one
    Possible duplicate question: Re-sort json jquery result for a specific field - lexxl
  • @lexxl there is sorted by value, and I need by key. Moreover, the .sort function is shown there, and as I said, the function displays an error - Shuhratjon Jumaev

2 answers 2

As already written, sorting an object does not make sense, you can either select fields by previously sorted keys, or you can first parse the fields of the object into an array and sort it already. Like that:

 var src = { 143: {foo: 43}, 131: {foo: 31}, 132: {foo: 32}, 136: {foo: 36}, 139: {foo: 39}, 144: {foo: 44}, 142: {foo: 42} } // Разберем исходный объект в массив dst var dst = []; for (var key in src) { dst.push({ key: key, value: src[key] }); } // Теперь отсортируем массив dst dst.sort(function(a, b) { return a.key > b.key; }); console.log(dst); 

Or a bit shorter with lodash / es6:

 var src = { 142: {foo: 42}, 131: {foo: 31}, 132: {foo: 32}, 136: {foo: 36}, 139: {foo: 39}, 143: {foo: 44}, 144: {foo: 44} } var dst = _.sortBy(_.map(src, (v, k) => ({v, k})), 'k'); console.log(dst); 

http://jsbin.com/kikobaz/edit?js,console

    Object properties are not ordered, they cannot be sorted.

    Definition of an Object from ECMAScript 3

    4.3.3 Object

    An object is a member of the type Object. It is an unordered collection of properties. This is a function.

    ECMAScript 6

    9.1.11 [[Enumerate]] ()

    When the [[Enumerate]] is taken, the following steps are taken:

    1. Return an Iterator object (25.1.1.2) The iterator object is inherited from% IteratorPrototype% (25.1.2). It is not necessary to conform to the rules specified below.