Search code examples
javascripthtmlarraysjavascript-objectstemplate-literals

How can I display an array of strings of an object as spans in a JS template literal?


I have an array of objects. In each object there is a key with a value of an array of strings (the number of strings changes in each object). How can I display each string of the array as <span> in a JS template literal?

If the array contains 2 strings, than 2 <span> should appear, If 3 strings, 3 <span> etc.

Code:

let items = [{
  "id": 1,
  "name": "item 1",
  "captionTags": ["Stills", "Animation", "Virtual Reality"]
},
{
  "id": 2,
  "name": "item 2",
  "captionTags": ["Configurator", "Animation", "Application"]
},
{
  "id": 3,
  "name": "item 3",
  "captionTags": ["Stills", "Configurator"]
}];

function displayItems() {
  let itemsContainer = document.querySelector('.items-container');
  itemsContainer.innerHTML = '';
  items.forEach(item => {

    itemsContainer.innerHTML += `
        <div class="items-wrapper">
        <div class="item-caption">
            <span class="item-caption-col">
                <h3>${item.name}</h3>
                <span class="item-caption-tags">
                I WANT TO DISPLAY HERE EACH ELEMENT OF CAPTION TAGS ARRAY IN EACH OBJECT 
               AS SPANS 
                </span>
            </span>
        </div>
    </div>`
  });
};


displayItems();

Thank you in advance for your help!


Solution

  • map over the items, and map over the tags returning string literals. But because map returns a new array just make sure you join it up into a string at the end.

    const items=[{id:1,name:"item 1",captionTags:["Stills","Animation","Virtual Reality"]},{id:2,name:"item 2",captionTags:["Configurator","Animation","Application"]},{id:3,name:"item 3",captionTags:["Stills","Configurator"]}];
    
    function displayItems(items) {
      return items.map(item => {
        const captions = item.captionTags.map(tag => `<span>${tag}</span>`).join('');
        return (
          `<h3>${item.name}</h3><div>${captions}</div>`
        );
      }).join('');
    }
    
    document.querySelector('div').innerHTML = displayItems(items);
    <div />