Javascript:按降序对对象(不是数组)进行排序

编程入门 行业动态 更新时间:2024-10-11 09:29:58
本文介绍了Javascript:按降序对对象(不是数组)进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道默认情况下对象是按升序或我们插入的方式排序的,但我需要按降序对对象进行排序的最佳方法.例如:

I know objects are by default sorted out in ascending order or the way we will insert but I need the best way to sort the object in descending order. Ex:

Input x = { a: {}, b: {}, c: {}, d: {} } Output: x = { d: {}, c: {}, b: {}, a: {} }

我尝试了以下解决方案,它有效,但这是一个好的做法还是我可以在这方面做得更好?

I tried the below solution, It works but is it a good practice or can I get anything better on this?

x= Object.keys(x).sort().reverse().reduce((obj, key) => { obj[key] = x[key] return obj }, {})

推荐答案

您可以使用 Array.sort 方法.我相信这只会在第一级深度上排序

You can use the Array.sort method. I believe this will only sort on the first level depth

const list = { a: "4", c: "2", b: "3", d: "1" } const sortedList = {}; Object.keys(list).sort().reverse().forEach(function(key) { sortedList[key] = list[key]; });

更多推荐

Javascript:按降序对对象(不是数组)进行排序

本文发布于:2023-11-11 08:54:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   降序   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!