I tried many solutions on this resource, nothing helps, the data comes in api, I have no opportunity to change something in them.

There is another json, but a very large and multi-level one, the same with it.

Tell me why chrome automatically sorts it? It is critical that the sorting be preserved.

<script> var dataUsers = { "3662": "Дмитрий Смирнов", "4356": "Олеся Лазарева", "2435": "Сергей Кузнецов", "2626": "Илья Брагин", "2624": "Артем Фокин", "3626": "Елена Борисова", "2352": "Анна Куликова", "2523": "Олег Трофимов" }; console.log(dataUsers); </script> 

  • if you need sorting, then why don't you use an array? - ThisMan
  • @ThisMan, How to do this? I get already in the form of json'a - OksanaDee
  • Well, let the server form the array, not the object - ThisMan
  • @ThisMan, this api is used by hundreds of people, they are unlikely to change something for me - OksanaDee
  • one
    First, you do not have JSON, but a JS object. Secondly, in each first directory it is indicated that the order of the keys in the object is not guaranteed. As it has already been written three times, use arrays. - Alexey Ten

1 answer 1

There are no instructions in the specification that the keys in the object should be sorted (otherwise, by what rule?). Behind the scenes though, the keys are still sorted:

The convention says that if the property name is a non-numeric string, then such keys are always sorted in the same order in which they were assigned. It happened so for historical reasons and it is difficult to change it: a lot of the finished code will break.

On the other hand, if the property name is a number or a numeric string, then all modern browsers sort such properties for internal optimization purposes.

Read more

In your case, you can create your own array of keys, which will be sorted according to your principles.

 const dataUsers = { "3662": "Дмитрий Смирнов", "4356": "Олеся Лазарева", "2435": "Сергей Кузнецов", "2626": "Илья Брагин", "2624": "Артем Фокин", "3626": "Елена Борисова", "2352": "Анна Куликова", "2523": "Олег Трофимов" }; // сортируем по возрастанию const sortedDataKeys = Object.keys(dataUsers) .sort((a, b) => parseInt(a) > parseInt(b)); const sortedDataUsers = sortedDataKeys .map(key => ({key, value: dataUsers[key]})); console.log(sortedDataUsers); 

All the magic in this line

 const sortedDataKeys = Object.keys(dataUsers) .sort((a, b) => parseInt(a) > parseInt(b)); 

Here sorting takes place using the sort method, you can pass any function to sort
Read more

  • It is a pity that there is no solution, this code is the same, sorts in ascending order. And how to at least make the sorting descending? - OksanaDee
  • @OksanaDee Well, here's the line .sort((a, b) => parseInt(a) > parseInt(b)); You can stuff any function here, you need to decrease, then replace > with < - ThisMan