我将地图初始化为:
var map = new Map();
当我console.log(map)
时,我得到:
testCreateBadAppointmentRequest:
{ name: 'testCreateBadAppointmentRequest',
time: 0.02926,
status: 'Passed' },
testAppointmentRequestAPI:
{ name: 'testAppointmentRequestAPI',
time: 0.051030000000000006,
status: 'Passed' },
我想在值的时间属性上对此地图进行排序。 我如何在nodejs中做到这一点? 是否有现成的排序功能?
答案 0 :(得分:2)
您需要先将Map
转换为Array
,然后使用内置sort
并提供回调:
const sorted = Array.from(map).sort(function(a, b) {
if (a.time < b.time) return -1;
if (a.time > b.time) return 1;
return 0;
});
答案 1 :(得分:1)
Map订单由广告订单决定。
应该注意的是,作为对象地图的地图,尤其是字典字典,只会映射到对象的插入顺序 - 这是随机的而不是有序的。
使用Array.from或使用地图上的spread operator可迭代将地图转换为数组。然后对数组进行排序:
const map = new Map()
map.set('testCreateBadAppointmentRequest', { name: 'testCreateBadAppointmentRequest', time: 0.02926, status: 'Passed' });
map.set('testAppointmentRequestAPI', { name: 'testAppointmentRequestAPI', time: 0.051030000000000006, status: 'Passed' });
// convert map to array
console.log('array', [...map.entries()]);
const array = Array.from(map);
// sort (inverse sort to change your current sort)
array.sort((x, y) => y[1].time - x[1].time);
console.log('sorted', array);
// create new map with objects pairs in the desired order:
const timeSortedMap = new Map(array);
console.log('sorted map', [...timeSortedMap]);
答案 2 :(得分:0)
您必须创建一个新的Map对象,因为Map对象按插入顺序迭代其元素。
const inputMap = new Map(
[
['testCreateBadAppointmentRequest',
{
name: 'testCreateBadAppointmentRequest',
time: 0.02926,
status: 'Passed'
}
],
['testAppointmentRequestAPI',
{
name: 'testAppointmentRequestAPI',
time: 0.051030000000000006,
status: 'Passed'
},
],
['another',
{
name: 'name',
time: 0.0001,
status: 'Passed'
},
]
]);
const sortedMap = new Map([...inputMap.entries()].sort((entryA, entryB) => entryB[1].time - entryA[1].time));
for (const value of sortedMap.values()) {
console.log(value)
}
&#13;