Search code examples
node.jsarraysobjectejsarray.prototype.map

Cant Map() Through An Array Of Objects


Been trying to solve this one for quite a while now. I am saving an array which contains objects to my data base. When I try to map() through it to retrieve the object's properties, it's just rendering nothing.

This is the app.js code :

app.get("/:plasticcategory/product/:plasticproduct", (req, res) => {

   const plasticCategory = _.startCase(_.toLower(req.params.plasticcategory));

   const plasticProduct =  req.params.plasticproduct;

   Product.find({category: plasticCategory, title: plasticProduct},'alt', (err, foundItem) => {

     if(err){

       console.log(err)

     }else {

       console.log(foundItem);

      res.render('alternatives', {altProduct: foundItem});

     }

   });

 });

When I console.log(foundItem) the result is [ { _id: 5f5f9b2a9f999b1e9009072b, alt: [ [Object] ] } ]

This is my ejs code(trying to render the alt's array objects properties:

    <% altProduct.map(alt => {%>

     <div class="col-lg-3">

       <h1><%=alt.altTitle %></h1>

       <img src="<%=alt.altImage%>" alt="alt-image">

       <a href="<%=alt.altUrl %>">Get it now!</a>

     </div>

    <% }) %>

I have added images to make it more clear, thank you <3 enter image description here


Solution

  • When you render the template, I see you call it like this:

    res.render('alternatives', {altProduct: foundItem});
    

    Where foundItem is the array [{ id: 'something', alt: [{ someObject }] }].

    This is an array of results. Each of those results has a key called 'alt' with items in it. If you want to render all of those items together, you will need to compile them all into a single array. (This is called 'flat-mapping'.)

    Starting inside the else block of the callback of Product.find:

    const itemArrays = foundItem.map(item => item.alt); // Get the inner array from each result
    const allAlternativeProducts = [].concat(...itemArrays); // Collect all these products into a single array
      res.render('alternatives', {altProduct: allAlternativeProducts});