将多个值(数组)输出到HTML时,不显示JSON值

时间:2019-12-26 09:21:22

标签: javascript html json

我正在通过fetch()遍历JSON对象。

我想访问对象中的一个对象,并通过键,值对对其进行迭代,并通过列表项将值输出到HTML。

当我尝试输出值时,我只会得到powerstats的最后一个值(有6个)

我需要在此处更改什么以使所有值正确显示在页面上?

我试图创建一个for循环并遍历value.length,但是value.length给了我2个答案。

随时使用提供的api密钥。

 function get_hero(rand_number) {
    const api_key = '10156555926000957';
    let hero_id = rand_number;
    let hero_url = `https://www.superheroapi.com/api/${api_key}/${hero_id}`;

    fetch(hero_url)
    .then(res => { 
      return res.json();
    })
    .then( data => {

      let ps = data.powerstats;

      Object.entries(ps).forEach(([key, value]) => {
        console.log(key + ' - ' + value) // key - value

        console.log(value.length)

        const smt = `<ul>
                      <li>${value}</li>
                      <li>${value}</li>
                      <li>${value}</li>
                      <li>${value}</li>
                      <li>${value}</li>
                      <li>${value}</li>
                    </ul>`;
        const power_stats = document.getElementById('powerstats');
        power_stats.innerHTML = smt;
      })

    })
    .catch(function() {
      console.log('error')
    })
  } 

browser output and console output

2 个答案:

答案 0 :(得分:1)

SD还没喝咖啡,XD

所以您的问题是一次又一次地用smt替换所有power_stats.innerHTML = smt;。您想使用element.appendChild(element)添加到列表中。不覆盖

.then(data => {

        const ps = data.powerstats;
        const power_stats = document.getElementById('powerstats');
        const list = document.createElement(`ul`)
        power_stats.appendChild(list)


        Object.entries(ps).forEach(([key, value]) => {
            console.log(key + ' - ' + value) // key - value

            console.log(value.length)

            const smt = document.createElement(`li`)
            smt.innerText = `The heroes ${key} is ${value}`
            list.appendChild(smt)
        })

    })

答案 1 :(得分:0)

当前,您的函数返回void,因此您不必等待fetch,因此您应该返回promise:

function get_hero(rand_number) {
    const api_key = '10156555926000957';
    let hero_id = rand_number;
    let hero_url = `https://www.superheroapi.com/api/${api_key}/${hero_id}`;

    return fetch(hero_url)
    .then(res => { 
      return res.json();
    })
    .then( data => {

      let ps = data.powerstats;

      Object.entries(ps).forEach(([key, value]) => {
        console.log(key + ' - ' + value) // key - value

        console.log(value.length)

        const smt = `<ul>
                      <li>${value}</li>
                    </ul>`;
        const power_stats = document.getElementById('powerstats');
        power_stats.innerHTML = smt;
      })

    })
    .catch(function() {
      console.log('error')
    })
  } 

使用:

get_hero(123).then(() => console.log('done!'));

(对我来说https://www.superheroapi.com/没有响应,所以也许这不是唯一的问题)