有没有办法在JavaScript对象中对键进行排序/排序? [英] Is there a way to sort/order keys in JavaScript objects?
本文介绍了有没有办法在JavaScript对象中对键进行排序/排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如以下
var data = {
'States': ['NSW', 'VIC'],
'Countries': ['GBR', 'AUS'],
'Capitals': ['SYD', 'MEL']
}
for (var item in data) {
console.log(item);
}
打印
States
Countries
Capitals
是有一种方法可以按字母顺序排序,以便打印
Is there a way to sort alphabetically so that it prints
Capitals
Countries
States
推荐答案
不在对象本身内:对象的属性集合是无序的。
Not within the object itself: the property collection of an object is unordered.
您可以做的一件事是使用 Object.keys()
,然后对Array进行排序,然后迭代它。 / p>
One thing you could do is use Object.keys()
, and sort the Array, then iterate it.
Object.keys(data)
.sort()
.forEach(function(v, i) {
console.log(v, data[v]);
});
不支持ECMAScript第5版的浏览器的补丁(实现):
Patches (implementations) for browsers that do not support ECMAScript 5th edition:
这篇关于有没有办法在JavaScript对象中对键进行排序/排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文