按名称升序和降序对对象进行排序应该怎么做?



我试图找到一个解决方案,可以找到一些接近但还没有的东西。Javascript排序一个对象的键基于另一个数组?我想按ABC升序和降序排序,但我不知道从哪里开始。

const Accounts = {
'thing': {
password: '123',
}
}
const sortedKeys = Object.getOwnPropertyNames(Accounts).sort();
//This returns the names but not the passwords

如果我对你的问题理解正确的话,那么它本质上是这个问题的重复。

从链接问题的评论中:在ecmascript中,对象属性的顺序是非标准的,所以你不能直接做你想做的。

我是这样做的:

const Accounts = {
'thing': {
password: '123',
}
} 
//get array keys and sort them
let sorted_keys = Object.keys(Accounts).sort();
//if you need your values too then use keys to access
sorted_keys.forEach(function(key) {//access each key and map to its value
let value = Accounts[key]
//do whatever with value
}
const sortedKeys = Object.getOwnPropertyNames(Accounts).sort();

上面的sortedKeys将包含一个排序键数组,如您所见。然后可以将排序的键映射到它们的值,从而得到一个排序的对象。

代码是我刚才解释的一个简单版本:

const Accounts = {
thing: { password: "123 }
}
const sortedAccounts = Object.keys(Accounts)
.sort()
.reduce((accumulator, key) => {
accumulator[key] = obj[key];
return accumulator;
}, {});

最新更新