js对map排序,后端返回有序的LinkedHashMap类型时前端获取后顺序依旧从小到大的解决方法
-
js对map排序,后端返回有序的LinkedHashMap类型时前端获取后顺序依旧从小到大的解决方法
-
[ { "2020": [ { "id": 39, "createTime": "2020-10-15T22:29:20.016", "year": 2020, "monthDay": "10-15", "title": "冒泡排序" }, { "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": "### 博客" } ] } ]
-
浏览器获取结果变成了:
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0vkNViJ4-1683592135147)(C:\Users\quyanliang\AppData\Roaming\Typora\typora-user-images\1683592070705.png)]
-
所以后端就算进行了排序处理,但是浏览器还是有自己的想法,在这里就要进行前端处理了:
-
//先把获取到的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)
-
可以从打印信息看出来已经正确排序了:文章来源:https://www.toymoban.com/news/detail-446257.html
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-n7mKsFXf-1683592135147)(C:\Users\quyanliang\AppData\Roaming\Typora\typora-user-images\1683592110064.png)]文章来源地址https://www.toymoban.com/news/detail-446257.html
到了这里,关于js对map排序,后端返回有序的LinkedHashMap类型时前端获取后顺序依旧从小到大的解决方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!