Search code examples
javascriptarraysjsonprototypejs

Iterate json object array and sort it based on key with Protoype JS


Sorry if this question is a duplicate but I have to ask it. I am using prototype JS for reading JSON data from a file. JSON data looks like this;

{
    "metaData": {
        "date": "2014-10-06"
    },
    "listOf": [
        {
            "fname": "bill",
            "id": 23
        },
        {
            "fname": "tom",
            "id": 35
        },
        {
            "fname": "jerry",
            "id": 12
        },
        {
            "fname": "batman",
            "id": 68
        },
        {
            "fname": "superman",
            "id": 55
        },
        {
            "fname": "sp-m/super",
            "id": 55
        },
    ]
}

In my code I need to access "listOf" key/array and then I want to loop through each element and to sort those elements base on "fname" key. I am reading this data through an ajax request. Below is that code;

new Ajax.Request('/file.json', {
                    method:'get',
                    onSuccess: function(transport){
                        var json = transport.responseText.evalJSON();
                        console.log(json);
                    }
                });

Now the VAR JSON contains the require data but I don't know how to access "listOf" data and iterate through it.

I tried to use .each function like this;

json.list.each(alert);

but it only printed " object OBJECT".

Please give me some help to resolve this issue.

P.S: Please tyr to use prototype JS for an answer but no Jquery.


Solution

  • You can access the listOf collection property using its name:

    json.listOf
    

    So if you wanted to sort the array you could try using the .sort() javascript method:

    json.listOf.sort(function(a, b) {
        if (a.fname > b.fname) {
            return 1;
        } else if (a.fname < b.fname) {
            return -1;
        }
        return 0;
    });
    
    // At this stage json.listOf will contain the sorted in-place array using the `fname` property
    

    and here's a sample jsfiddle illustrating this in action.