How can I sort a JSON array?

How to output this JSON element in the correct order by its value?

var json = { "message": { "90": "Adidas", "2": "Armani", "89": "Casio", "1": "Diesel", "72": "DKNY", "88": "Fossil", "4": "Hamilton", "6": "Luminox", "99": "Michael Kors", "968": "Mont Blanc Pens", "3": "Nixon", "959": "Nooka", "92": "Seiko", "91": "Tendence", "7": "Tissot" } }; var str = ''; for (var i in json.message) { str += json.message[i]+'\n'; } alert(str); 

he notifies in the following order -

Diesel
Armani
Nixon
Hamilton
Luminox
Dkny
Fossils
Casio
Adidas
Tendence
Seiko
Michael Kors
Nooka
Mont Blanc Pens

But I want it in order below

Adidas
Armani
Casio
Diesel
Dkny
Fossils
Hamilton
Luminox
Michael Kors
Mont Blanc Pens
Nixon
Nooka
Seiko
Tendence
Tissot

Can someone suggest me which approach should I take in order to get the right order?

Any help would be greatly appreciated!

+4
source share
5 answers

Assuming the items are listed in alphabetical order by their value:

 var values = []; for(var i in json.message) { values.push(json.message[i]); } var str = values.sort().join('\n'); 

Update

To form an array of key-value pairs ordered by their (string) value:

 var values = []; for(var i in json.message) { values.push({ key: i, value: json.message[i] }); } values.sort(function(a, b) { return a.value.localeCompare(b.value); }); var str = values.map(function (kvp) { return kvp.value; }).join('\n'); 
+8
source
 var message = object.message; var brands = Object.keys(message) .map(function(key) { return message[key]; }) .sort(); alert(brands.join('\n')); 
+1
source

Add a leading 0 to each index. For instance:

 var json = { "message": { "090": "Adidas", "02": "Armani", "089": "Casio", "01": "Diesel", ... 
0
source

using the undescore.js JS library is pretty simple, just do:

 json.message=_.sortBy(json.message,function(i){return i;}) 
0
source

You can sort it this way, this is sorting based on values:

 function sortJsonMap(data){ var values = []; var keys = []; for(var i in data) { keys.push(i); values.push(data[i]); } values.sort(); var map = new Object(); for(var i in values) { map[keys[i]]=values[i]; } return map; 

}

0
source

Source: https://habr.com/ru/post/1391810/


All Articles