按键排序JavaScript对象 [英] Sort JavaScript object by key
问题描述
我需要按键对JavaScript对象进行排序。
I need to sort JavaScript objects by key.
因此如下:
{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
将成为:
{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }
推荐答案
此问题的其他答案已过时,从未匹配实施现实,并且正式在ES6 / ES2015规范发布后变得不正确。
The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6/ES2015 spec has been published.
请参阅有关属性迭代顺序的部分在探索ES6 中由Axel Rauschmayer :
See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:
所有迭代属性键的方法都执行所以按照相同的顺序:
All methods that iterate over property keys do so in the same order:
- 首先是所有数组索引,按数字排序。
- 然后按照创建顺序排列所有字符串键(不是索引)。
- 然后按顺序排列所有符号它们是在哪里创建的。
所以是的,JavaScript对象 实际上是有序的,并且可以更改其键/属性的顺序。
So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.
以下是按字母顺序按键/属性对对象进行排序的方法:
Here’s how you can sort an object by its keys/properties, alphabetically:
const unordered = {
'b': 'foo',
'c': 'bar',
'a': 'baz'
};
console.log(JSON.stringify(unordered));
// → '{"b":"foo","c":"bar","a":"baz"}'
const ordered = {};
Object.keys(unordered).sort().forEach(function(key) {
ordered[key] = unordered[key];
});
console.log(JSON.stringify(ordered));
// → '{"a":"baz","b":"foo","c":"bar"}'
使用 var
代替 const
以获得与ES5引擎的兼容性。
Use var
instead of const
for compatibility with ES5 engines.
这篇关于按键排序JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!