本文介绍了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:按降序对对象(不是数组)进行排序
发布评论