Hi All
I have a long list of Json entries in the usual formatting key:value, - for example :
“UTB”: “Cancel”,
“ATB”:“Delete”,
and so on - I need to sort them out alphabetically by value - like in the example above are ok (c, d) even if the keys are not.
Is there a regex that can help me with this job? I am going insane trying to do it manually.
thanks
You should consider an object to not have an order to it’s properties, because it’s undefined in the spec(even though most browsers do lead you to believe there’s a reliable order to it).
Change it to an array(which has an order defined by numeric index), like
var arr = [
["UTB", "Cancel"],
["ATB", "Delete"]
];
Then you can write yourself a custom sorting function.
arr.sort(function(a, b){
if (b[1] == a[1]) {
return 0;
}
return b[1] < a[1] ? -1 : 1;
});
Thanks for the reply crmalibu - will test it now - unfortunately it’s a txt file I got which is part of a bigger project, a plain text file that populates a dropdown, in fact the values will become the select options text and the key the options values…if that makes sense.
So I need sorting the select options text to be in alphabetical order.
g
Oh, so it’s not really json, you just decided to convert the text file into a json object? Well that makes it easy. Just convert it to an array format like I posted.
it is already a json file and needs to be the same after the changes, with “keys”:“values” but the values are unordered now and need to be ordered in alphabetical order, I am still stuck
- got so many of these to go through.
here how it starts but the list of controllers is massive
“controllers”:{
“UTB”: “Cancel”,
“ATB”:“Delete”,
convert to array > sort > convert back to desired format. When you convert back, the order in which you define each property will be the “order” that browsers use.
I have worked it out… the solution was simpler that what I thought.
I swap the “key”:“values” position with a simple regex, so it becomes “values”:“key” , use the text editor to order the long list alphabetically and then run the regex again to put things back to “key”:“values”…phew at last, many thanks for your input crmalibu