skip to Main Content

I’m in a pickle because my function is not displaying anything in an array.
I know there are 3 objects in an array (taken from an API):

PC
macOS
PlayStation

but when I try this code:

    function platforms() {
    let platform = [];
    platform = details.platforms;

    for (let i = 0; i < platform.length; i++) {
        console.log(platform[i].platform.name);
        platform[i].platform.name;
    }
}

console.log works just fine but another line – platform[i].platform.name; – is showing me UNDEFINED.
Everything else works just fine. I can take titles, screenshots, score etc but not arrays unfortunately 🙁

And if it helps here is my slightly bigger piece of code

function displayGameDetails(details) {

function platforms() {
    let platform = [];
    platform = details.platforms;

    for (let i = 0; i < platform.length; i++) {
        console.log(platform[i].platform.name);
        platform[i].platform.name;
    }
}

resultGrid.innerHTML = `
<div class="box">
    <p class="fourPara">${platforms()}</p>
</div >
`;
}

2

Answers


  1. Chosen as BEST ANSWER

    It works! Big thanks to Mr. Polywhirl and David. Like David said I had to use RETURN keyword and Mr.Polywhirl pointed me in the right direction, the map() method!

    (noob)SOLUTION

    function displayGameDetails(details) {
    
    const platformArray = details.platforms;
    const platformAll = platformArray.map(function (singlePlatform) {
        return singlePlatform.platform.name;
    })
    
    resultGrid.innerHTML = `
    <div class="box">
    <p class="fourPara">${platformAll.join("<br/>")}</p>
    </div>
    `;
    }
    

  2. You could simplify this greatly:

    const resultGrid = document.querySelector('.results-grid');
    
    function displayPlatforms(platforms) {
      return platforms.map(({ name }) => {
        console.log(name);
        return `<span data-platform="${name}">${name}</span>`;
      }).join(', ')
    }
    
    function displayGameDetails(details) {
      resultGrid.innerHTML = `
        <div class="box">
            <p class="fourPara">
              Rating: ${details.rating}
            </p>
            <p class="fourPara">
              ${displayPlatforms(details.platforms)}
            </p>
        </div >
      `;
    }
    
    displayGameDetails({
      rating: 'mature',
      platforms: [
        { name: 'Windows' },
        { name: 'macOS' },
        { name: 'PlayStation' }
      ]
    });
    [data-platform="Windows"]     { color: teal; }
    [data-platform="macOS"]       { color: magenta; }
    [data-platform="PlayStation"] { color: blue; }
    <div class="results-grid"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search