javascripttemplate-literalstagged-templates

How to get a random object from an array of objects and display in a tagged template literal?


I am using a tagged template literal to output an array of objects, but I want to display a random object, and not all the objects.

How do I display a random object from the array of objects?

const archetypes = [
  {
    type: 'The Magician',
    desc: 'A powerful figure who has harnessed the ways of the universe to achieve key goals.',
    strengths: 'omniscience, omnipotence, discipline',
    weaknesses: 'corruptibility, arrogance',
  }, {
    type: 'The Lover',
    desc: 'The romantic lead who’s guided by the heart.',
    strengths: 'humanism, passion, conviction',
    weaknesses: 'naivete, irrationality'
  }
];

const archetypesTemplate = types => {
  return `
    <h3><span><i>${types.type}</i></span></h3>
    <p class="desc">${types.desc}</p>
    <h3><span><u>Strengths:</u> ${types.strengths}</span></h3>
    <h3><span><u>Weaknesses:</u> ${types.weaknesses}</span></h3>  
  `;
}

const randomArchetypeGenerator = () => {
  let randomArchetype = archetypes[Math.floor(Math.random() * archetypes.length)];
  document.getElementById('archetype').innerHTML = `${archetypes.map(archetypesTemplate).join('<hr>')}`;
}

randomArchetypeGenerator();
<h3>Archetype: <br><div id="archetype"></div></h3>


Solution

  • So, use randomArchetype instead of map the whole array.

    const archetypes = [
      {
        type: 'The Magician',
        desc: 'A powerful figure who has harnessed the ways of the universe to achieve key goals.',
        strengths: 'omniscience, omnipotence, discipline',
        weaknesses: 'corruptibility, arrogance',
      }, {
        type: 'The Lover',
        desc: 'The romantic lead who’s guided by the heart.',
        strengths: 'humanism, passion, conviction',
        weaknesses: 'naivete, irrationality'
      }
    ];
    
    const archetypesTemplate = types => {
      return `
        <h3><span><i>${types.type}</i></span></h3>
        <p class="desc">${types.desc}</p>
        <h3><span><u>Strengths:</u> ${types.strengths}</span></h3>
        <h3><span><u>Weaknesses:</u> ${types.weaknesses}</span></h3>  
      `;
    }
    
    const randomArchetypeGenerator = () => {
      let randomArchetype = archetypes[Math.floor(Math.random() * archetypes.length)];
      document.getElementById('archetype').innerHTML = archetypesTemplate(randomArchetype)
    }
    
    randomArchetypeGenerator();
    <h3>Archetype: <br><div id="archetype"></div></h3>