Search code examples
javascriptjsonsortingflickr

Sorting a multi-dimensional JSON object in Javascript


I tried finding an answer to this on here, but kept coming up with real simplistic examples, so here goes:

I am pulling a photoset list from Flickr's API, and it needs to be in javascript. Anyhow, their response is unlike most others places the value to sort within a sub-object like so:

"photoset":[
    {..."photos":"15", "videos":0, "title":{"_content":"Shocktoberfest 2012"}, "description":{"_content":""}, "needs_interstitial":0, "visibility_can_see_set":1, "count_views":"0", "count_comments":"0", "can_comment":0, "date_create":"1351829136", "date_update":"1351829309"}
    ...
    ...
    ...
]

How can I sort on the title for instance, when the value is within in a sub-object like it is?


Solution

  • You could provide a callback to the Array.sort and return the usual -1, 0, 1 for sorting:

    some_response.photoset.sort(function(a, b){ 
        return a.title._content.localeCompare(b.title._content); 
    });