简体   繁体   中英

Having trouble accessing required info through array object javascript

我要访问的内容的图片

A more detailed picture

I am trying to access platform.name for all the parent_platforms however i am getting a bunch of commas in return. I am pretty sure i am supposed to use the.map function to iterate through all platform.name in the parent_platform. Basically my desired output would be names of all the platforms like this PC, PlayStation, Xbox Here is my current code so far. Thanks

function showGames(game)
{
  game.forEach(game => {
    console.log(game);
    const card = document.createElement('div');
    card.classList.add('card');
    card.innerHTML = `
    <div class="card-top">
      <img src="${game.background_image}" alt="" class="card-image">
    </div>
    <div class="card-bottom">
      <h1>${game.name}</h1>
      <h3>Release date: ${game.released}</h3>
      <p>Platforms: ${game.parent_platforms.map(platform => platform.name)}</p>
      <p>Rating: ${game.rating}</p>
    </div>
    `;
    main.appendChild(card);
  })
}

Your use of map will give an array of the platform names, but what then you'll get a standard array representation (conversion to string) which is unlikely to be what you actually want in the HTML representation.

You might like to try using Array.join, like this:

${game.parent_platforms.map(platform => platform.name).join()}

This will insert a string formatted such as "PC,PlayStation,Xbox" into the HTML output. If you want a different separator, add it as an argument to join, thus:

${game.parent_platforms.map(platform => platform.name).join(', ')}

The structure of the rest of the code is problematic as other commenters have pointed out, but this answers your question as to use of map.

As @danh mentions, there is also a missing level of dereferencing (I'm renaming the parent_platforms element to make it clear):

${game.parent_platforms.map(element => element.platform.name).join()}

If this is what needs to be mapped...

[{"platform":{"id":1,"name":"PC","slug":"pc"}},{"platform":{"id":2,"name":"PlayStation","slug":"playstation"}},{"platform":{"id":3,"name":"Xbox","slug":"xbox"}}]

and this is the mapping code...

game.parent_platforms.map(platform => platform.name)

You will certainly get an array of nulls. There's another level of object nesting there, as follows...

game.parent_platforms.map(platform => platform.platform.name)
//                                             ^^^^^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM