0

I would like to iterate over a list of objects and get an array as the results of the items that pass a condition. Something like this:

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);
  });

I don't want any error callback if the condition isn't passed. Only an array with the ids of the elements.

1 Answer 1

2

you don't want map, you want 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);
  });

This, however, gives you unaltered (but filtered) items, if you want to map them (switch from full items to just ids) as well, you would to do that in the final callback. If you really want to do both in a single step, I would suggest using each and constructing the array manually, use eachSeries if you need to maintain order.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.