Dave
Dave

Reputation: 1492

How to print an HashMap by value and not by key with Jquery

That's the code to list the map into a jsp with jQuery.

function getCustomerMap() {
    $.ajax({
        url: serverUrl + "/getMap",
        success: function (data) {
            var map = JSON.parse(data);
            $.each(map, function (key, value) {
                $('#users').append('<li data-user="' + key + '"><a>' +  value.name + '</a></li>');                    
            });

This is how the HashMap JSON comes to jsp:

enter image description here

Like you can see, the map is ordered by name.

But this is how the HashMap is listed:

enter image description here

The map is listed from smaller key to biggest!

I would that the map was listed like comes to jsp..

Upvotes: 1

Views: 3573

Answers (1)

Tap
Tap

Reputation: 6522

When the string representation of the map is received on the client side, it becomes a plain old javascript object, and the keys are its fields. Their natural sort order is "1", "2", "3", "4", "5", "6". This is why it's displayed in that order. One way to display it the way you want is to convert it to an array of objects (the map values), and sort by name with javascript:

function getCustomerMap() {
    $.ajax({
        url: serverUrl + "/getMap",
        success: function (data) {
            var map = JSON.parse(data);
            var arr = new Array();
            for (var key in map)
                arr.push(map[key]); // add the map values to the array

            // sort the array by name
            arr.sort(function(a, b){
                if (a.name < b.name)
                    return -1;
                if (a.name > b.name)
                    return 1;
                return 0;
            });

            // iterate by array index and append the list items.
            // now you use the id field of the objects as your data-user values.
            for (var i in arr)
                $('#users').append('<li data-user="' + arr[i].id + '"><a>' + arr[i].name + '</a></li>');
        }
    });
}

Upvotes: 1

Related Questions