java - 如何使用 Jquery 按值而不是按键打印 HashMap

标签 java jquery json jsp hashmap

这是使用 jQuery 将 map 列出到 jsp 中的代码。

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>');                    
            });

这就是 HashMap JSON 来到 jsp 的方式:

enter image description here

如您所见, map 是按名称排序的。

但这就是HashMap的列出方式:

enter image description here

map 按从小到大的顺序排列!

我希望 map 像 jsp 一样列出..

最佳答案

当客户端接收到 map 的字符串表示形式时,它就变成了一个普通的旧 JavaScript 对象,键是它的字段。它们的自然排序顺序是“1”、“2”、“3”、“4”、“5”、“6”。这就是它按该顺序显示的原因。按照您想要的方式显示它的一种方法是将其转换为对象数组( map 值),并使用 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>');
        }
    });
}

关于java - 如何使用 Jquery 按值而不是按键打印 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228952/

相关文章:

jquery - 有没有一个 jquery 插件可以显示类似微软向导的东西?

javascript - 如何在 Angularjs Controller 中的 Click 上更新我的 html

区分大小写的 JSON Unmarshal 结构

Java Swing : Inner JFrame class closes main window on close

java - 在Java中打印矩阵行

java - 如何从结果集中查找每列中最长字段的长度

java - 对spring Controller 进行单元测试——是使用MockMvc还是直接调用方法

javascript - (Javascript) CSS width() 属性在窗口调整大小之前不应用

jquery - 验证失败时无法获取所需输入元素周围的红色矩形

jQuery ajaxForm 返回 .json 文件