【问题标题】:How do I loop through an array and select elements that don't have index value using JS如何循环遍历数组并使用 JS 选择没有索引值的元素
【发布时间】:2021-06-20 15:35:33
【问题描述】:

我正在尝试创建一个循环,该循环将从数组中的每个元素中选择“照片”。但是,它们没有索引号,所以我不能使用传统的 for 循环,每次都使用循环迭代来选择下一个对象。我似乎找不到允许选择器在每次循环发生时更改的方法。

这就是我所拥有的:

function fetchHalls() {
    halls = [];
    fetch(`https://www.data.brisbane.qld.gov.au/data/dataset/d14761ac-9bd9-4712-aefd-4bace8ca7148/resource/d7a4821d-eb68-454a-9615-356e17fd805b/download/bcccommunityhalls.json`)
    .then(resp => resp.json())
    .then(data => {
        halls = halls.concat(data);
        console.log(halls[0].Halls[ 'Acacia Ridge Hall' ].Description[4].Photos);
    });
}

我基本上想将“Acacia Ridge Hall”更改为阵列中的下一个大厅名称,并为阵列中的许多大厅执行此操作。我也尝试过,但 '.length' 什么也没返回。

这是结构的外观的 sn-p:

【问题讨论】:

  • 能否给我们看一个接收到的数据示例
  • 当你到达最后一项时会发生什么?

标签: javascript arrays loops


【解决方案1】:

这是我的解决方案:

for(let hall of Object.keys(data.Halls)) {
  // Here hall is the hallname, e.g, "Acacia Ridge Hall"
  // and data.Halls[hall] // is the value
  const urls = data.Halls[hall]?.Description[4]?.Photos;
  
  if(urls) {
    // whatever you want to do with the urls
  }
}

【讨论】:

    【解决方案2】:

    首先,如果您确定从服务器返回的数据始终为 Pascal Case,则可以去掉 concat。 我在下面的代码中假设它总是返回 Pascal Case 中的数据。您可以使用以下两种方法之一来循环从服务器返回的对象:

    1. Object.values(大厅)
    2. Object.keys(大厅)

    示例代码:

        var halls = [];
        fetch(`https://www.data.brisbane.qld.gov.au/data/dataset/d14761ac-9bd9-4712-aefd-4bace8ca7148/resource/d7a4821d-eb68-454a-9615-356e17fd805b/download/bcccommunityhalls.json`)
            .then(resp => resp.json())
            .then(data => {
                halls = data.Halls;
                //1st method
                for (let value of Object.values(halls)) {
                    // Here loop through the description to access photo elements 
                    console.log('value', value.Description) 
                }
                //2nd method
                Object.keys(halls).map(function (element, index, array) {
                    console.log("element", element);
                    console.log("index", index);
                    console.log("array", array);
                });
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 2018-11-02
      • 2011-10-07
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多