Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

javascript - 按键对JavaScript对象进行排序(Sort JavaScript object by key)

I need to sort JavaScript objects by key.(我需要按键对JavaScript对象进行排序。)

Hence the following:(因此,以下内容:) { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' } Would become:(会成为:) { 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }   ask by vdh_ant translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(此问题的其他答案已过时,从未与实现现实相匹配,并且由于ES6 / ES2015规范已发布而正式变得不正确。)

See the section on property iteration order in Exploring ES6 by Axel Rauschmayer :(请参阅Axel Rauschmayer的“ 探索ES6”中有关属性迭代顺序的部分 :) 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.(然后按创建顺序排列所有符号。) So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.(所以,是的,JavaScript对象其实都是有序的,他们的键的顺序/属性是可以改变的。) 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().forEach(function(key) { ordered[key] = unordered[key]; }); console.log(JSON.stringify(ordered)); // → '{"a":"baz","b":"foo","c":"bar"}' Use var instead of const for compatibility with ES5 engines.(使用var而不是const来与ES5引擎兼容。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...