按键对 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.
参见关于属性迭代顺序的部分 在 Axel Rauschmayer 的 Exploring ES6 中:
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().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
},
{}
);
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屋!