7

In the following example I am trying to render a list of posts (title, body and their tags):

const container = $('.container');
posts.forEach((post)=> {
 container.append(
`<div>
  <h2>${post.title}</h2>
  <p>${post.body}</p>
  <div>
   ${post.tags.map((tag) => {
     `<span>${tag.name}</span>`
   })}
  </div> 
 </div>`)
});

The output however renders an extra comma between tags. I have tried to to outputting 'test' instead of the actual tag names as well as swapping the span tag for a different html tag, but the result is still the same.

I have tried to search for this issue, but haven't had any luck finding anyone else having this issue with template literals.

jacobdo
  • 1,605
  • 3
  • 15
  • 34

1 Answers1

17

That's exactly how Array.join() works by default (which is called when implicitly stringifying an array), adding a comma between array entries - which is what is returned by map() -> an array. You can easily get rid of it by calling it yourself, passing an empty string as argument to join()

${post.tags.map((tag) => `<span>${tag.name}</span>`).join('')}

Note that you would need to return from map too...

baao
  • 71,625
  • 17
  • 143
  • 203