Sort a simple JSON object

Possible duplicate:
Sort JavaScript object by property value

Since I noticed that the browser cannot guarantee JSON order through an ajax call ( link ), I am having some problems sorting the JSON element with javascript after the ajax call.

I found several topics about this problem, but nothing gave me a clear solution for the simple structure of my JSON object. I have only 1 segment with a lot of data. I know there are a lot of topics about this, even on stackoverflow, but not a single topic handles this simple json structure.

For instance:

{ "158":"Banana", "265":"Pear", "358":"Apple", "864":"Peach" } 

How can I sort this object by fruit name, not id? I would like to have this object at the end:

 { "358":"Apple", "158":"Banana", "864":"Peach" "265":"Pear", } 

Thanks in advance.

+4
source share
2 answers
 var kk = { "158":"Banana", "265":"Pear", "358":"Apple", "864":"Peach" } var keys = []; var datas = {} $.each(kk, function(key, value){ keys.push(value) datas[value] = key; }) var aa = keys.sort() var sorted ={} $.each(aa, function(index, value){ sorted[datas[value]] = value; }) 
+2
source
 var someObject = { "158":"Banana", "265":"Pear", "358":"Apple", "864":"Peach" }; //flip the name/value pairs Object.prototype["reverseObject"] = function() { var name; var newObject = {}; for(name in this) { if(typeof this[name] !== 'function') { newObject[this[name]] = name; } } return newObject; } var reversedObject = someObject.reverseObject(); console.log(reversedObject); var i; var properties = []; //get all the property names $.each(reversedObject, function(key, value) { if(reversedObject[key] !== this) properties.push(key); }); properties.sort(); var sortedObject = []; //iterate the array using the order specified for(i = 0; i < properties.length; i += 1) { sortedObject[properties[i]] = reversedObject[properties[i]]; //document.writeln(properties[i] + " : " + reversedObject[properties[i]]); } var sortedObject = sortedObject.reverseObject(); console.log(sortedObject); 

Fiddle

Creates a sorted array of property names in alphabetical order. Then this array is used to index the object. As a result, you will get the exact object that you requested.

0
source

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


All Articles