Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array map in template literal renders an extra comma between items [duplicate]

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.

like image 501
jacobdo Avatar asked Jun 10 '18 08:06

jacobdo


People also ask

What is `` in JS?

Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.

What is ${} in HTML?

The ${} syntax allows us to put an expression in it and it will produce the value, which in our case above is just a variable that holds a string! There is something to note here: if you wanted to add in values, like above, you do not need to use a Template Literal for the name variable.

Which of the following correctly describe what a template literal can be used for in JavaScript code?

Template literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.

What is a tagged template literal?

Tagged templates. A more advanced form of template literals are tagged templates. Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.


1 Answers

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

like image 56
baao Avatar answered Sep 22 '22 01:09

baao