Is it possible to sort a ES6 map object?

后端 未结 11 1729
滥情空心
滥情空心 2020-11-28 21:34

Is it possible to sort the entries of a es6 map object?

var map = new Map();
map.set(\'2-1\', foo);
map.set(\'0-1\', bar);

results in:

11条回答
  •  误落风尘
    2020-11-28 22:15

    The snippet below sorts given map by its keys and maps the keys to key-value objects again. I used localeCompare function since my map was string->string object map.

    var hash = {'x': 'xx', 't': 'tt', 'y': 'yy'};
    Object.keys(hash).sort((a, b) => a.localeCompare(b)).map(function (i) {
                var o = {};
                o[i] = hash[i];
                return o;
            });
    

    result: [{t:'tt'}, {x:'xx'}, {y: 'yy'}];

提交回复
热议问题