node.js - node 字典序排序
迷茫
迷茫 2017-04-17 11:32:54
0
3
967

如何用node做字典序排序,比如b=1,a=2,c=3, 排完后是a=2,b=1,c=3,

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
黄舟

Copied from @xelz, but avoiding some of the pitfalls of old JavaScript:

jslet dict = {a: 3, b:1, c:2};
for (let key of Object.keys(dict).sort()) {
  console.log(key, dict[key]);
}

Tested and passed in Firefox 28.

刘奇

The dictionary is unordered, but there is a default order for traversing the dictionary.

If the subject wants to change the default order of traversing the dictionary, just

function sortDict(dict) {
    var dict2 = {}, 
        keys = Object.keys(dict).sort();

    for (var i = 0, n = keys.length, key; i < n; ++i) {
        key = keys[i];
        dict2[key] = dict[key];
    }

    return dict2;
}

However, this method seems to be invalid for numeric keys. When you need numeric keys, add a prefix (in fact, it is not a real dictionary without a prefix)


Downstairs, please don’t use in when traversing the array. This kind of error is difficult to find. . .

function sortEach(dict, fn) {
    var keys = Object.keys(dict).sort();

    for (var i = 0, n = keys.length, key; i < n; ++i) {
        key = keys[i];
        fn(dict[key], key, dict);
    }
}

Thank you Evian, you can still do it:

javascriptfor (var key of Object.keys(dict).sort()) {
    // do something with dict[key]
}

阿神

Sorting a dictionary is a false proposition, because the dictionary is 无序 and you cannot change its order

If you want to 有序遍历 it, use

for (var key in Object.keys(dict).sort()) {
    // do something with dict[key]
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template