0

I'm getting data from an API to be used to display game genres on screen. The issue is the way the code is currently written displays the entire object, but I only want specific values.


    const onGameSelect = game => {
    
      
       document.querySelector("#summary").innerHTML = `
       <article class="media">
         <figure class="media-left">
          <p class="image">
           <img src="${game.background_image}" />
           </p>
           </figure>
            <div class="media-content">
              <div class="content">
                <h1>${game.name}</h1>
                <h4>${JSON.stringify(game.genres)}</h4>
                </div>
    
           </article>
           `    
                
    };

Result:

[
   {
      "id":4,
      "name":"Action",
      "slug":"action"
   },
   {
      "id":11,
      "name":"Arcade",
      "slug":"arcade"
   },
   {
      "id":14,
      "name":"Simulation",
      "slug":"simulation"
   },
   {
      "id":51,
      "name":"Indie",
      "slug":"indie"
   },
   {
      "id":59,
      "name":"Massively Multiplayer",
      "slug":"massively-multiplayer"
   }
]

What i want it to display on screen instead:

Action
Arcade
Simulation
Indie
Massively Multiplayer
2
  • 1
    JSON.stringify(game.genres.map(genre => genre.name)) Commented Sep 13, 2022 at 19:44
  • 2
    something like game.genres.map(o=>o.name).join(" ")? Commented Sep 13, 2022 at 19:44

1 Answer 1

1

You can just map it out: obj.genres.map(o => o.name).join(" ")

let obj = {genres: [{"id":4,"name":"Action","slug":"action"},{"id":11,"name":"Arcade","slug":"arcade"},{"id":14,"name":"Simulation","slug":"simulation"},{"id":51,"name":"Indie","slug":"indie"},{"id":59,"name":"Massively Multiplayer","slug":"massively-multiplayer"}]};
let genres = obj.genres.map(o => o.name).join(" ")
console.log(genres)

// or

document.querySelector("#summary").innerHTML = `${obj.genres.map(o => o.name).join(" ")}`;
<div id="summary"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

thank you ! Where did you find how to do this?
This site actually. When I started trying to answer easy questions, I learned alot about how to update my old methods with newer ways. The link in my answer is the absolute best source of javascript info. It's now something I refer to quite often.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.