js对map排序,后端返回有序的LinkedHashMap类型时前端获取后顺序依旧从小到大的解决方法

在后端进行时间倒序查询后,返回map类型的数据,在postman获取是这样:

[
    {
        "2020": [
            {
                "id": 39,
                "createTime": "2020-10-15T22:29:20.016",
                "year": 2020,
                "monthDay": "10-15",
                "title": "java数据结构61:冒泡排序"
            },
            {
                "id": 37,
                "createTime": "2020-10-14T11:44:12.163",
                "year": 2020,
                "monthDay": "10-14",
                "title": "这是博客标题13"
            }
        ],
        "2019": [
            {
                "id": 28,
                "createTime": "2019-10-15T18:57:41.409",
                "year": 2019,
                "monthDay": "10-15",
                "title": "这是博客标题5"
            },
            {
                "id": 27,
                "createTime": "2019-10-15T18:57:38.442",
                "year": 2019,
                "monthDay": "10-15",
                "title": "这是博客标题4"
            },
            {
                "id": 26,
                "createTime": "2019-10-15T18:57:36.086",
                "year": 2019,
                "monthDay": "10-15",
                "title": "这是博客标题3"
            }
        ],
        "2018": [
            {
                "id": 25,
                "createTime": "2018-10-15T18:57:31.986",
                "year": 2018,
                "monthDay": "10-15",
                "title": "这是博客标题2"
            },
            {
                "id": 24,
                "createTime": "2018-10-15T18:57:27.428",
                "year": 2018,
                "monthDay": "10-15",
                "title": "这是博客标题1"
            }
        ],
        "2017": [
            {
                "id": 12,
                "createTime": "2017-10-14T11:44:12.163",
                "year": 2017,
                "monthDay": "10-14",
                "title": "### 锟桑的第一篇博客"
            }
        ]
    }
]

浏览器获取结果变成了:

js对map排序,后端返回有序的LinkedHashMap类型时前端获取后顺序依旧从小到大的解决方法_第1张图片

所以后端就算进行了排序处理,但是浏览器还是有自己的想法,在这里就要进行前端处理了:

                    //先把获取到的json对象转成map
                    let map = new Map();
                    //archive就是接口返回的json对象
                    for (let year in archive) {
                        map.set(year,archive[year]);
                    }
                    //把map转换为array就可以排序了
                    let arr = Array.from(map);
                    arr.sort(function (a,b) {
                        //map转成array后,下标0为key,下标1为value
                        //这里根据年份进行倒序排序
                        return b[0]-a[0];
                    });
                    console.log(arr)

可以从打印信息看出来已经正确排序了:

js对map排序,后端返回有序的LinkedHashMap类型时前端获取后顺序依旧从小到大的解决方法_第2张图片

虽然解决了问题,但是这无疑会增加前端的工作量,所以推荐的做法是,在后端再定定义个类,比如:

public class ArchivePlusVo {
    private String year;
    private List list;
}

然后把要返回的Map对象转换成List再返回就好了。

你可能感兴趣的:(java,js,js,javascript,java,map,json)