John Cooper
John Cooper

Reputation: 7631

Sorting my JSON response

{
    "JsonResult": {
        "List": [{
            "Subject": "Something",
            "Type": 0,
            "TypeDescription": "Referral"
        }],
     }
}

This is my sample json response i get while hitting my service, after that i have a button which carries option like Subject, Type and TypeDescription.

How can i sort the Json Response based on the parameter i send.

function sortItems(jsonResponse,paramater){
          var sorted =  jsonResponse.List.sort( function(a, b) {
          var nameA = a.paramater.toLowerCase(),
          nameB = b.paramater.toLowerCase();
          return nameA.localeCompare(nameB);
}

Here is the sort function i am using, but its not working. I already have my JSON response and i need to sort at runtime based on the argument i send.

Upvotes: 0

Views: 1363

Answers (2)

Thalaivar
Thalaivar

Reputation: 23632

Here is a Js Fiddle for you which would give you a deeper insight.

http://jsfiddle.net/spechackers/EdAWL/

<script type="text/javascript">
        onerror = function (a, b, c) {
            alert([a, b, c]);
        };
    </script>
<script type="text/javascript">
    var x = {
        "JsonResult": {
            "List": [{
                "Subject": "My book report on J. K. Rowling's <u>Harry Potter</u> series.",
                "Date": "Jan 25th 2009",
                "Type": "Book Report",
                "Class": "English"
            }, {
                "Subject": "My book report on Charles Dickens' <u>Oliver Twist</u> novel.",
                "Date": "May 1st 2003",
                "Type": "Book Report",
                "Class": "English"
            }, {
                "Subject": "My book report on J. R. R. Tolkien's <u>The Lord of the Rings</u> series.",
                "Date": "Aug 7th 2007",
                "Type": "Book Report",
                "Class": "English"
            }, {
                "Subject": "The civil war in a nutshell.",
                "Date": "Feb 26th 2009",
                "Type": "Essay",
                "Class": "History"
            }, {
                "Subject": "How does the republican party manage if we life in a democracy?",
                "Date": "Apr 5th 2010",
                "Type": "Essay",
                "Class": "Government"
            }, {
                "Subject": "A bogus entry",
                "Date": "Jan 1st 2000",
                "Type": "Bogus",
                "Class": "None"
            }, {
                "Subject": "Zombie followers don't prove anything.",
                "Date": "Nov 2nd 2004",
                "Type": "Essay",
                "Class": "Religion"
            }]
        }
    };
</script>
<script type="text/javascript">
    if (typeof Object.prototype.toSource == 'undefined') {
        Object.prototype.toSource = function () {
            return (typeof JSON != 'undefined' && typeof JSON.stringify == 'function') ? JSON.stringify(this) : this.toString();
        };
    }

    function sortItems(jsonResponse, paramater) {
        var sorted = jsonResponse.List.sort(

        function (a, b) {
            var nameA = a[paramater].toLowerCase();
            var nameB = b[paramater].toLowerCase();
            return nameA.localeCompare(nameB);
        });
        return sorted;
    }

    function makeRow(ar) {
        return "<tr><td>" + ar[0] + "</td><td>" + ar[1] + "</td><td>" + ar[2] + "</td><td>" + ar[3] + "</td></tr>";

    }
</script>
<script type="text/javascript">
    var mySortedList = sortItems(x.JsonResult, "Subject");
    //alert(mySortedList.toSource());
    var outTable = "<table>";
    outTable += "<tr><th>Subject</th><th>Date</th><th>Type</th><th>Class</th></tr>";
    for (var i = 0; i < mySortedList.length; i++) {
        outTable += makeRow([mySortedList[i].Subject, mySortedList[i].Date, mySortedList[i].Type, mySortedList[i].Class]);
    }
    outTable += "</table>";
    document.write(outTable);
</script>

Upvotes: 0

user504674
user504674

Reputation:

function sortItems(jsonResponse, paramater) {
      var sorted =  jsonResponse.JsonResult.List.sort(function(a, b) {
          var nameA = a[paramater].toLowerCase(), //take note, []
          nameB = b[paramater].toLowerCase(); //same here
          return nameA.localeCompare(nameB);
      });
}

'paramater', the second argument, is a string representing the key to be looked for, and not a direct field accessor statement. Therefore it cannot be accessed from the json using a dot operator.

Also, be careful: It should be:

jsonResponse.JsonResult.List.sort

A while back, I wanted to do the same: See here for some tricks:
Stackoverflow: Sorting array of custom objects in JavaScript

Upvotes: 1

Related Questions