如何使用async.js映射数组

How to map an array with async.js?

本文关键字:映射 数组 js async 何使用      更新时间:2023-09-26

我想迭代对象列表,并获得一个数组作为传递条件的项的结果。像这样:

var list = [{foo:"bar",id:0},{foo:"baz",id:1},{foo:"bar",id:2}];
  async.map(list, function(item, cb) {
    if (item.foo === "bar")
      cb(null, item.id);
    else
      cb(); // do nothing
  }, function(err, ids) {
    console.log(ids);
  });

如果条件没有通过,我不想要任何错误回调。只有包含元素id的数组

你不需要map,你需要filter:

var list = [{foo:"bar",id:0},{foo:"baz",id:1},{foo:"bar",id:2}];
  async.filter(list, function(item, cb) {
    if (item.foo === "bar")
      cb(true);  // include
    else
      cb(false); // do not include
  }, function(err, items) {
    console.log(items);
  });

,然而,给你未改变(但过滤)的项目,如果你想映射它们(从完整的项目切换到只有id),你会在最后的回调中这样做。如果您真的想在一个步骤中完成这两个操作,我建议使用每个操作并手动构造数组,如果需要保持顺序,请使用eachSeries。