【问题标题】:Node.js - Only displaying last element in JSON rsponseNode.js - 仅显示 JSON 响应中的最后一个元素
【发布时间】:2019-10-15 17:37:27
【问题描述】:

我正在解析远程 API 生成的 JSON 响应。我遍历响应并将所需的字段存储在值中。我从 pug 模板创建我的 homeCard 元素并将值传递给它。这个问题是它只显示 json 响应中的最后一个元素(性感海滩 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 响应

【问题讨论】:

  • "这里是 JSON 响应" 请以文本形式发布代码、标记、JSON 等数据等。作为文本,而不是作为 图片的文字。为什么:meta.stackoverflow.com/q/285551/157247 另外,发布的 JSON 无效(缺少前导 [),但我认为您只是截断了图片...

标签: node.js json parsing pug


【解决方案1】:

您正在为 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);
  });

【讨论】:

  • 或者更好的是,使用map。您还可以使用速记属性和解构。 const homeCards = response.data.map(({name: title, summary: description, url: link}) =&gt; ({title, link, description}));
  • @Sharvin K 您的解决方案有效。所有的 json 都被解析成卡片,但现在正在渲染一张额外的卡片,上面有注释。我在 for 循环之外声明了 var homeCards = [4]
  • @T.J. Crowder 这个声明是在 for 循环内部还是外部?我声明它是 inide 并得到错误: hoemCards is not defined on line 33
  • 没关系。我解决了这个问题。我声明 var homeCards = []
  • @Gabriel - 根本没有循环:pastebin.com/v5rEqvKG(嗯,循环是 map 调用...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2018-10-30
相关资源
最近更新 更多