简体   繁体   中英

How to display nested object json with forEach method

I'm trying to build an app using the free rawg api. I have this json

results: 
added_by_status: {yet: 463, owned: 3266, beaten: 428, toplay: 2237, dropped: 101, …}
background_image: "https://media.rawg.io/media/games/26d/26d4437715bee60138dab4a7c8c59c92.jpg"
clip: {clip: "https://media.rawg.io/media/stories-640/f78/f789c8011d52e0ffac76b11a88fabee7.mp4", clips: {…}, video: "59pvij73-N0", preview: "https://media.rawg.io/media/stories-previews/fad/fad39fae9b0809ab42ff03586e7204de.jpg"}
dominant_color: "0f0f0f"
esrb_rating: {id: 5, name: "Adults Only", slug: "adults-only", name_en: "Adults Only", name_ru: "Только для взрослых"}
genres: (3) [{…}, {…}, {…}]
id: 41494
metacritic: 68
name: "Cyberpunk 2077"
parent_platforms: (3) [{…}, {…}, {…}]
platforms: (5) [{…}, {…}, {…}, {…}, {…}]
playtime: 19
rating: 4.12
rating_top: 5
ratings: (4) [{…}, {…}, {…}, {…}]
ratings_count: 841
released: "2020-12-10"
reviews_count: 883

and my javascript

const APIURL = 'https://api.rawg.io/api/games?page_size=50&dates=2020-01-01,2021-12-31&ordering=-added';
        const main = document.querySelector('main');

        async function getGames() {
            let resp = await fetch(APIURL);
            let respData = await resp.json();   

            console.log(respData);

            respData.results.forEach(game => {

            const { background_image, metacritic, name, platforms, platforms: {platform} } = game;
             
            console.log(platforms[0].platform.name);
            
                let gameEl = document.createElement('div');
                gameEl.classList.add('game');
                gameEl.innerHTML = `
            
            <div class="image" style="background-image: url(${background_image})"></div>
            <div id="game-info" class="game-info" >
                <div id="platforms" class="platforms"></div> 
                <h3>${name}</h3>
                <span class="${getRatingClass(metacritic)}">${metacritic}</span>
            </div> `;

                main.appendChild(gameEl)
                
            });
            return respData;
        }
        function getRatingClass(voto) {
            if (voto >= 80) {
                return 'green';
            } else if (voto >= 50) {
                return 'orange';
            } else {
                return 'red';
            }
        }
        getGames();

Now everything works but I can't display the nested array "platform" which has "platform", "name", "id" and "slug" inside. Like this:

platforms: Array(5)
0:
platform:
id: 4
name: "PC"
slug: "pc"
__proto__: Object
__proto__: Object
1: {platform: {…}}
2: {platform: {…}}
3: {platform: {…}}
4: {platform: {…}}

how do i display the platforms in the div with id = "platforms"? Thanks!

You have a few issues, but you inevitably want this:

`<div id="platforms" class="platforms">
  ${platforms.map(({ platform: { name } }) =>
    `<span class="platform">${name || ''}</span>`
  ).join('')}
</div>`
  1. First, respData.results is not an array, make sure it is enclosed in one.
  2. Second, just destructure the platforms and deal with it later when it comes to mapping.

I modified your object to include the follwoing:

"platforms": [
  { "platform": { "name": "Playstation" } },
  { "platform": { "name": "PC" } }
]

Basic example using local data

 const respData = { "results": [{ "added_by_status": { "yet": 463, "owned": 3266, "beaten": 428, "toplay": 2237, "dropped": 101 }, "background_image": "https://media.rawg.io/media/games/26d/26d4437715bee60138dab4a7c8c59c92.jpg", "clip": { "clip": "https://media.rawg.io/media/stories-640/f78/f789c8011d52e0ffac76b11a88fabee7.mp4", "clips": {}, "video": "59pvij73-N0", "preview": "https://media.rawg.io/media/stories-previews/fad/fad39fae9b0809ab42ff03586e7204de.jpg" }, "dominant_color": "0f0f0f", "esrb_rating": { "id": 5, "name": "Adults Only", "slug": "adults-only", "name_en": "Adults Only", "name_ru": "Только для взрослых" }, "genres": [{}, {}, {}], "id": 41494, "metacritic": 68, "name": "Cyberpunk 2077", "parent_platforms": [{}, {}, {}], "platforms": [{ "platform": { "name": "Playstation" } }, { "platform": { "name": "PC" } }], "playtime": 19, "rating": 4.12, "rating_top": 5, "ratings": [{}, {}, {}, {}], "ratings_count": 841, "released": "2020-12-10", "reviews_count": 883 }] } const main = document.querySelector('main'); respData.results.forEach(game => { const { background_image, metacritic, name, platforms } = game; let gameEl = document.createElement('div'); gameEl.classList.add('game'); gameEl.innerHTML = ` <div class="image" style="background-image: url(${background_image})"></div> <div id="game-info" class="game-info" > <div id="platforms" class="platforms"> ${platforms.map(({ platform: { name } }) => `<span class="platform">${name || ''}</span>` ).join('')} </div> <h3>${name}</h3> <span class="${getRatingClass(metacritic)}">${metacritic}</span> </div> `; main.appendChild(gameEl) }); function getRatingClass(voto) { if (voto >= 80) return 'green'; else if (voto >= 50) return 'orange'; else return 'red'; }
 .platforms { display: flex; }.platform { display: inline-flex; margin-right: 0.5em; border: thin solid grey; padding: 0.25em; }
 <main></main>

Full example using API call

 const main = () => { const mainEl = document.querySelector('main'); fetch('https://api.rawg.io/api/games?page_size=50&dates=2020-01-01,2021-12-31&ordering=-added').then(response => response.json()).then(respData => render(respData.results, mainEl)); }; const render = (games, targetEl) => { games.forEach(game => { const { background_image, metacritic, name, platforms } = game; let gameEl = document.createElement('div'); gameEl.classList.add('game'); gameEl.innerHTML = ` <div class="image" style="background-image: url('${background_image}')"></div> <div class="game-info" > <div id="platforms" class="platforms"> ${platforms.map(({ platform: { name } }) => `<span class="platform">${name || ''}</span>` ).join('')} </div> <h3>${name}</h3> <span class="rating ${getRatingClass(metacritic)}">${metacritic || 'N/A'}</span> </div> `; targetEl.appendChild(gameEl); }); }; const getRatingClass = vote => { if (vote == null) return 'grey'; else if (vote >= 80) return 'green'; else if (vote >= 50) return 'orange'; else return 'red'; } main();
 .platforms { display: flex; }.platform { display: inline-flex; margin-right: 0.5em; border: thin solid grey; padding: 0.25em; }.rating { display: block; width: 2em; height: 1.5em; line-height: 1.5em; text-align: center; }.grey { background: #AAA; }.green { background: #0F0; }.orange { background: #F70; }.red { background: #F00; }.game-info { margin-bottom: 1em; padding-bottom: 0.5em; border-bottom: thin solid grey; }.image { width: 178px; height: 100px; background-size: contain; margin-bottom: 0.5em; }
 <main></main>

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