javascript - 按键排序 JavaScript 对象

标签 javascript sorting

我需要按键对 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:

  1. First all Array indices, sorted numerically.
  2. Then all string keys (that are not indices), in the order in which they were created.
  3. 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/

相关文章:

java - 在 Java 中通过多个比较器对列表进行排序的有效方法

比较 char 数组元素

java - Java中如何优化这个方法?我的时间超出限制

javascript - 油猴:喜欢还是讨厌?

php - ksort 不尊重 LC_COLLATE

javascript - Vue 元素内部迭代

javascript - 单击 <a> 标记时不运行 jQuery 函数

c - 按字母顺序对结构中的数据进行排序

javascript - getElementsByClassName 不返回长度

javascript - 如何为目录中的每个文件创建元素 | Javascript | NodeJS |埃杰斯