问题
I have this Express route:
app.use('/stop_jobs', function (req, res, next) {
const jobId = req.query && req.query.job_id;
const stopped : Array<any> = [];
for (let j of runningJobs.keys()) {
if(j.id === jobId){
stopped.push(j.stopThisInstance());
}
}
res.json({success: {stopped}});
});
where
const runningJobs = new Map<CDTChronBase,CDTChronBase>();
(CDTChronBase is a class)
the above works, but I'd like to simplify it if possible, something like this:
app.use('/stop_jobs', function (req, res, next) {
const jobId = req.query && req.query.job_id;
const stopped = runningJobs.keys().filter(j => {
return j.id === jobId;
})
.map(v => {
return j.stopThisInstance()
});
res.json({success: {stopped}});
});
but for the life of me, I cannot figure out how to get an Array instance of any of the methods on Map. Is there a way to use map/filter type methods on Map objects?
回答1:
I think you're looking for
const stopped = Array.from(runningJobs.keys())
.filter(j => j.id === jobId)
.map(j => j.stopThisInstance());
Apart from that, you could also use filter and map functions that work on iterators such as the .keys()
of a Map.
回答2:
Since the key and value are same object, you can extract one of them and then covert it into an array.
If you convert map into array directly, it will be in [[key, value],[key, value], ...]
structure. Then pick index 0:
const stopped = Array.from(runningJobs)
.map(job => job[0])
.filter(key => key.id === jobId)
.map(key => key.topThisInstance());
来源:https://stackoverflow.com/questions/49501690/using-map-filter-behavior-on-map-instance