This question has already been answered:

Tell me how to sort the object in which other objects in rows and numbers? Sorting an array of objects by rows is simple:

var test = [ { name: "Бананы", price: 2000 }, { name: "Сливы", price: 1000 }, { name: "Тыква", price: 1200 }, { name: "Ананасы", price: 3000 } ]; test.sort(function(obj1, obj2) { if (obj1.name < obj2.name) return -1; if (obj1.name > obj2.name) return 1; return 0; }); console.log(test); 

And what would you need so it was about:

 var test = { '0':{ name: "Бананы", price: 2000 }, '1':{ name: "Сливы", price: 1000 }, '2':{ name: "Тыква", price: 1200 }, '3':{ name: "Ананасы", price: 3000 } }; test.sort(function(obj2, obj1) { if (obj1.name < obj2.name) return -1; if (obj1.name > obj2.name) return 1; return 0; }); console.log(test); 

Need that used bananas and plums sorted alphabetically =)

Reported as a duplicate by the participants Grundy , HamSter , aleksandr barakin , cheops , rjhdby 24 Oct '16 at 6:42 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • the object cannot be sorted. In addition, it is not clear what is being done in the second example and what the result should be in the end - Grundy
  • @Grundy, presumably, requires sorting, just not an array of objects, but an object of objects. - user207618

1 answer 1

 var test = { '0': { name: "Бананы", price: 2000 }, '1': { name: "Сливы", price: 1000 }, '2': { name: "Тыква", price: 1200 }, '3': { name: "Ананасы", price: 3000 } }, tmp = []; // Преобразование в массив // ES2017 (сейчас работает в Chrome && FF) tmp = Object.values(test); // Старый, добрый цикл for(let key in test) if(test.hasOwnProperty(key)) tmp.push(test[key]); // Сортируем tmp = tmp.sort(function(obj2, obj1) { if(obj1.name < obj2.name) return 1; if(obj1.name > obj2.name) return -1; return 0; }); console.info(tmp); 

  • sort changes the original array. there is no need to assign it to yourself. Well, the output - an array, not an object, and it is not known what the author needed - Grundy
  • @Grundy, right, perhaps, but the keys are still digital. - user207618 pm
  • and you do not get an error here "" message ":" Uncaught TypeError: Object. Values ​​is not a function ","? - user3319778
  • one
    @ user3319778, this is a sign of the old browser. You can remove the line tmp = Object.values(test); She is for demonstration only. - user207618
  • Exactly, right now everything works well. Thank you, this is what you need! - user3319778