按键对 JavaScript 对象进行排序 [英] Sort JavaScript object by key

查看:21
本文介绍了按键对 JavaScript 对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  1. 首先是所有数组索引,按数字排序.
  2. 然后是所有字符串键(不是索引),按照它们的创建顺序.
  3. 然后是所有符号,按照它们的创建顺序.

是的,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆