Node.js-仅显示JSON响应中的最后一个元素

时间:2019-05-30 05:01:19

标签: node.js json parsing pug

我正在解析由远程API生成的JSON响应。我遍历响应并将所需的字段存储在值中。我从pug模板创建了homeCard元素,并将其值传递给了它。这个问题是,它仅显示json响应中的最后一个元素(Sexy Beach 3)。如何更改代码,以便每次通过循环时都创建家庭卡?

    const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,url,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data; 
    for (i=0; i<r.length; ++i){
      //create homecards with 
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
        var homeCards = [
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          ]
        console.log(title, description, link);
      }

          })
  .catch(err => {
      console.error(err);
  });

这是JSON响应

enter image description here

1 个答案:

答案 0 :(得分:2)

您正在为homecards数组对象分配相同的值,并且每次迭代时也会覆盖相同的数组。 您必须在循环外部声明homecards数组,然后将对象推入其中。

    const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,url,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data; 
    var homeCards = [];
    for (i=0; i<r.length; ++i){
      //create homecards with 
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
         homeCards.push({
            title: title,
            link: link,
            description: description,
          });
        console.log(title, description, link);
      }

          })
  .catch(err => {
      console.error(err);
  });