gpt4 book ai didi

javascript - 按键排序 JavaScript 对象

转载 作者:IT老高 更新时间:2023-10-28 11:01:39 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com