Home > Net >  Having trouble accessing required info through array object javascript
Having trouble accessing required info through array object javascript

Time:04-30

Picture of what i want to access

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 >
      <img src="${game.background_image}" alt="" >
    </div>
    <div >
      <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);
  })
}

CodePudding user response:

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)
//                                             ^^^^^^^^

CodePudding user response:

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()}
  • Related