-4

I'm a bit new to javascript so please be kind. I have a post that contains a for loop. And I'd like to re-write the loop with .map as It looks like I can do so here (is there a better way?) How can I do this?

here is my code..

app.post('/api/products', (req, res) => {
  let products = [];
  let id = null;
  let cart = JSON.parse(req.body.cart);
  if (!cart) return res.json(products);
  // TODO: replace for loop with .map
  for (var i = 0; i < data.products.length; i++) {
    id = data.products[i].id.toString();
    if (cart.hasOwnProperty(id)) {
      data.products[i].qty = cart[id];
      products.push(data.products[i]);
    }
  }
  return res.json(products);
});
Jessi
  • 791
  • 1
  • 12
  • 24
  • 1
    You'd have to map then filter because of the conditional in the `for` loop. Whether or not this is worth it is kind of a toss-up; I don't see a huge advantage to using map/filter here other than it's a bit nicer if you pull out some functionality. – Dave Newton May 17 '19 at 15:14
  • @Jamiec It doesn't matter which end you filter it on from a functionality standpoint. Obviously there'd be a performance penalty. – Dave Newton May 17 '19 at 16:11

2 Answers2

1

I don't think you can rewrite this with map unless you want null elements in your array. Probably should use reduce (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce):

let products = data.products.reduce((result, product) => {
  id = product.id.toString();
  if (cart.hasOwnProperty(id)) {
    product.qty = cart[id];
    result.push(product);
  }
  return result;
}, []);

I haven't tested it, but it should work.

jennyfofenny
  • 4,359
  • 2
  • 17
  • 15
-3

Pretty simple, map works like a each but allow to return transformed element. But you also need a filter function to remove elements you don't want.

For each object, transform it or not (set qty), then return it or null, then add a filter function to remove null elements :

return res.json(datas.products.map(function(e){

     if(cart[e.id.toString()])
     {
         e.qty = cart[e.id.toString()];
         return e;
     }
     else
     {
         return null;
     }

  }).filter(function(e){
     if(e)
       return true;
     else
       return false;
  });
);
Daphoque
  • 4,421
  • 1
  • 20
  • 31