Search code examples
javascriptecmascript-6ecmascript-2016

Is there a better way to refactor this for loop with map or reduce?


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

Solution

  • 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.