Using map/filter behavior on Map instance

北慕城南 提交于 2020-01-05 03:57:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!