Reputation: 4480
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
}, {})
Upvotes: 1
Views: 2885
Reputation: 44086
Use a Map to guarantee order while using Object.entries()
method to preserve key/value pairs.
Object.entries()
.reverse()
itMap()
guarantees order according to how it was entered)let obj = {a:{}, b:{}, c:{}, d:{}};
let rev = new Map(Object.entries(obj).reverse());
let ent = Object.fromEntries(rev);
console.log(ent);
See compatibility table for Object.fromEntries()
Upvotes: 1
Reputation: 343
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];
});
Upvotes: 1