【问题标题】:Confusion while trying to access and array inside of an array.尝试访问数组内部的数组时感到困惑。
【发布时间】:2018-12-03 07:19:03
【问题描述】:

例如,我正在使用 fetch api 从 NY Times api 中获取数据。在响应内部,有一个名为“Multimedia”的对象,其中包含图像。我创建了一个模板文字来获取必要的数据,但似乎无法获取任何图像。DEMO ON CODEPEN 这是我的代码:

const div = document.getElementById('article'),
      url = "https://api.nytimes.com/svc/topstories/v2/home.json?api-key=fd168d666e644fe29bbb534d757b374e";

fetch(url)
.then((response) => {return response.json(); })
.then(data => {  
  
  let article = data.results;
  console.log(article);

  return article.map(user => {
    let output = '<div class="container">';
    article.forEach(user => {
      output += `
      <article>
        <img src="${user.multimedia.url}">
        <h2>${user.title}</h2>
        <span class="author"><b>Author:</b> ${user.byline} | <b>Category: </b>${user.section}</span>
        <p>${user.abstract}</p>
        <a class="btn" href="${user.url}" target="_blank">View Article</a>
      </article>
    `
    });
    document.getElementById('article').innerHTML = output;
  })
})
.catch( error => { console.log(error); })
 
%body
  #article

我尝试使用 user.multimedia.url 访问图像,但似乎无法提取图像。任何关于为什么我无法完成这项工作的帮助或解释将不胜感激。谢谢!

【问题讨论】:

  • 看起来 user.multimedia 是一个对象数组,而不仅仅是一个值。您需要遍历数组或按索引选择所需的项目。这是一个使用数组中第一个图像的快速示例 - codepen.io/anon/pen/qKKGBy?editors=1010
  • 似乎变量user 与 Map 一起在 forEach 中使用,所以尝试更改变量名称。
  • @BrettGregson 非常感谢您的完美工作!
  • 谢谢@ThomasBrushel。我也将它作为答案发布给将来在这篇文章中结束的任何人

标签: javascript json xmlhttprequest fetch-api


【解决方案1】:

看起来 user.multimedia 是一个对象数组,而不仅仅是一个值。您需要遍历数组或按索引选择所需的项目:

user.multimedia[0].url

Here's a quick example using the first image in the array

【讨论】:

    【解决方案2】:

    你应该像这样遍历user.multimedia

    var imgs = "";
        article.map(user => {
          user.multimedia.map(i=>{
           imgs += "<img src="+i.url+">"
          })
    

    并在output 中将${imgs} 放在您想要图像的位置。有几张不同尺寸的图片,所以我认为你应该选择其中一张。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2016-02-13
      • 1970-01-01
      相关资源
      最近更新 更多