我需要按键对 JavaScript 对象进行排序。
因此如下:
{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
会变成:
{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }
最佳答案
这个问题的其他答案已经过时,从未与实际实现相匹配,并且在 ES6/ES2015 规范已经发布后,正式变得不正确。
见 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:
- First all Array indices, sorted numerically.
- Then all string keys (that are not indices), in the order in which they were created.
- Then all symbols, in the order in which they were created.
所以是的,JavaScript 对象是事实上是有序的,并且它们的键/属性的顺序是可以改变的。
您可以按照字母顺序按键/属性对对象进行排序:
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 引擎兼容。
关于javascript - 按键排序 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5467129/