1

Im having trouble showing image array it is showing undefined

here is my code:

  data.rows.forEach(function (row) {
    var attachments = JSON.parse(row.attachment);

    $("#records_row").append(
      "<tr>\
        <td>" +row.id +"</td>\
        <td>" + row.subject +"</td>\
        <td id='imagecol'>"+
          attachments.forEach(item => {
            "<img src='"+item+"' class='img-thumbnail'>" //This part is showing undefined
          })
          +"</td>\
       </tr>"
    );

  });

my array

(2) ['/images/footer-bg.jpg', '/images/hero-bg.jpg']
  • 3
    Please provide array for `data` – Ravi Ashara Oct 21 '21 at 07:24
  • Looks like you need to have `item` instead of `attachments[0]`. – guyaloni Oct 21 '21 at 07:26
  • 3
    There are two separate problems above: 1. The result of calling `forEach` is **always** `undefined` ([more](https://stackoverflow.com/questions/48368299/template-literals-with-a-foreach-in-it)). You probably wanted `map` (and then `.join("")` to make a single string from the result array). 2. Your callback function [doesn't return anything](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value). – T.J. Crowder Oct 21 '21 at 07:30
  • Thanks T.J. Crowder, that solves my problem. – Mike Tabag Estonanto Oct 21 '21 at 07:34

2 Answers2

0
var img = ""
attachments.forEach(item => {
            img += "<img src='"+attachments[0]+"' class='img-thumbnail'>" 
          })

array.forEach does not have a return value

Manfred Wippel
  • 1,946
  • 1
  • 15
  • 14
-1

Here is example for data with forEach

var data = [{
'attachment':'attachment',
'id':'id',
'subject':'subject'
},{
'attachment':'attachment',
'id':'id',
'subject':'subject'
},{
'attachment':'attachment',
'id':'id',
'subject':'subject'
}]

data.forEach(function (row) {
   console.log(row);
  });
Ravi Ashara
  • 1,177
  • 7
  • 16