为什么循环不会循环JSON数组

huangapple go评论64阅读模式
英文:

Why does loop doesn't loop JSON array

问题

以下是代码部分的翻译:

async function getAthletes() {

    const getPlayers = document.getElementById('getPlayers')

    await fetch('athlete.json', {
        method: 'GET'
    })
    .then((response) => response.json())
    .then(data => {

        const athletes = data.team.roster[0].athlete

        for(let i = 0; i < athletes.length; i++) {
            getPlayers.innerHTML += `<option value="${athletes[i].name}">${athletes[i].name}</option>`
        }
    }) 
}
<select id="getPlayers" data-category="Vote" data-action="click" data-label="Select Player">
    <option value="">Select player</option>
</select>

希望这对你有所帮助。

英文:

I have a list of athlete names in JSON format from a fetch. Using for loop, I want to grab all the names under roster > athlete > name and then inserting them into dropdown menu.

But for some reason the loop is not working. If I take out the loop and just grab a single athlete, it worked. Maybe I got confused about arrays and objects?

JSON code

{
    &quot;team&quot;: {
        &quot;color&quot;: &quot;000000&quot;,
        &quot;country&quot;: &quot;USA&quot;,
        &quot;roster&quot;: [
            {
                &quot;athlete&quot;: {
                    &quot;name&quot;: &quot;John Doe&quot;,
                    &quot;age&quot;: 20
                }
            },
            {
                &quot;athlete&quot;: {
                    &quot;name&quot;: &quot;Jane Doe&quot;,
                    &quot;age&quot;: 21
                }
            },
            {
                &quot;athlete&quot;: {
                    &quot;name&quot;: &quot;Jack Doe&quot;,
                    &quot;age&quot;: 22
                }
            },
            {
                &quot;athlete&quot;: {
                    &quot;name&quot;: &quot;Joe Doe&quot;,
                    &quot;age&quot;: 23
                }
            }
        ]
    }
}

I have a list of athlete names in JSON format from a fetch. Using for loop, I want to grab all the names under roster > athlete > name and then inserting them into dropdown menu.

But for some reason the loop is not working. If I take out the loop and just grab a single athlete, it worked. Maybe I got confused about arrays and objects?

JSON code

{
    &quot;team&quot;: {
        &quot;color&quot;: &quot;000000&quot;,
        &quot;country&quot;: &quot;USA&quot;,
        &quot;roster&quot;: [
            {
                &quot;athlete&quot;: {
                    &quot;name&quot;: &quot;John Doe&quot;,
                    &quot;age&quot;: 20
                }
            },
            {
                &quot;athlete&quot;: {
                    &quot;name&quot;: &quot;Jane Doe&quot;,
                    &quot;age&quot;: 21
                }
            },
            {
                &quot;athlete&quot;: {
                    &quot;name&quot;: &quot;Jack Doe&quot;,
                    &quot;age&quot;: 22
                }
            },
            {
                &quot;athlete&quot;: {
                    &quot;name&quot;: &quot;Joe Doe&quot;,
                    &quot;age&quot;: 23
                }
            }
        ]
    }
}

JS code

async function getAthletes() {

    const getPlayers = document.getElementById(&#39;getPlayers&#39;)

    await fetch(&#39;athlete.json&#39;, {
        method: &#39;GET&#39;
    })
    .then((response) =&gt; response.json())
    .then(data =&gt; {

        const athletes = data.team.roster[0].athlete

        for(let i = 0; i &lt; athletes.length; i++) {
            getPlayers.innerHTML += `&lt;option value=&quot;${athletes[i].name}&quot;&gt;${athletes[i].name}&lt;/option&gt;`
        }
    }) 
}

HTML

&lt;select id=&quot;getPlayers&quot; data-category=&quot;Vote&quot; data-action=&quot;click&quot; data-label=&quot;Select Player&quot;&gt;
    &lt;option value=&quot;&quot;&gt;Select player&lt;/option&gt;
&lt;/select&gt;

Hoping to get like this after the loop

&lt;select id=&quot;getPlayers&quot; data-category=&quot;pick&quot; data-action=&quot;click&quot; data-label=&quot;Select Player&quot;&gt;
    &lt;option value&gt;Select player&lt;/option&gt;
    &lt;option value=&quot;John Doe&quot;&gt;John Doe&lt;/option&gt;
    &lt;option value=&quot;Jane Doe&quot;&gt;Jane Doe&lt;/option&gt;
    &lt;option value=&quot;Jack Doe&quot;&gt;Jack Doe&lt;/option&gt;
    &lt;option value=&quot;Joe Doe&quot;&gt;Joe Doe&lt;/option&gt;
&lt;/select&gt;

答案1

得分: 3

只看一下你在语义上正在做什么:

const athletes = data.team.roster[0].athlete

你创建了一个名为athletes的变量,并将其值设置为一个运动员。某物的单个实例并不是某物的列表。在这个操作中,你指定了数组的索引0。如果你想循环遍历整个数组,不要仅使用其中一个元素。使用整个数组:

const athletes = data.team.roster; 

然后数组中的每个元素将类似于:

{
  "athlete": {
    "name": "John Doe",
    "age": 20
  }
}

因此,在循环中引用它的值将类似于:

athletes[i].athlete.name
英文:

Just look at what you're doing semantically here:

const athletes = data.team.roster[0].athlete

ou're creating a variable called athletes and setting its value to an athlete. A single instance of something is not a list of something. In that operation you specify index 0 of the array. If you want to loop over the entire array, don't use only one of its elements. Use the entire array:

 const athletes = data.team.roster; 

Then each element in the array would be like:

  &quot;athlete&quot;: {
    &quot;name&quot;: &quot;John Doe&quot;,
    &quot;age&quot;: 20
  }
}

So referencing a value on it in the loop would be something like:

 athletes[i].athlete.name 

答案2

得分: 1

主要问题是你试图索引运动员,而不是数组。队名单才是数组。你还在async/await的使用上有些混淆。以下可能会有所帮助:

async function getAthletes() {
  const getPlayers = document.getElementById('getPlayers');
  const response = await fetch('athlete.json');
  const data = await response.json();
  const roster = data.team.roster;
  for (let i = 0; i < roster.length; i++) {
    getPlayers.innerHTML += `<option value="${roster[i].athlete.name}">${roster[i].athlete.name}</option>`;
  }
}
英文:

The main issue is that you were trying to index the athlete, which is not the array. The roster is the array. You also had some mixed up use of async/await. This might be helpful:

async function getAthletes() {
  const getPlayers = document.getElementById(&#39;getPlayers&#39;)
  const response = await fetch(&#39;athlete.json&#39;);
  const data = await response.json();
  const roster = data.team.roster;
  for (let i = 0; i &lt; roster.length; i++) {
    getPlayers.innerHTML += `&lt;option value=&quot;${roster[i].athlete.name}&quot;&gt;${roster[i].athlete.name}&lt;/option&gt;`
  }
}

答案3

得分: 1

在这种情况下,更简单的方法是使用Array#map创建一个选项数组,然后可以使用Element#append将其添加到选择元素中。

const data = { team: { color: "000000", country: "USA", roster: [{ athlete: { name: "John Doe", age: 20 } }, { athlete: { name: "Jane Doe", age: 21 } }, { athlete: { name: "Jack Doe", age: 22 } }, { athlete: { name: "Joe Doe", age: 23 } }] } };
const getPlayers = document.getElementById('getPlayers');

getPlayers.append(...data.team.roster.map(o => new Option(o.athlete.name)));
<select id="getPlayers" data-category="Vote" data-action="click" data-label="Select Player">
    <option value="">Select player</option>
</select>

请注意,上述代码是JavaScript和HTML的示例,用于将数据添加到选择元素中。

英文:

A simpler method in this case is to use Array#map to create an array of options, which can be added to the select element with Element#append.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data={team:{color:&quot;000000&quot;,country:&quot;USA&quot;,roster:[{athlete:{name:&quot;John Doe&quot;,age:20}},{athlete:{name:&quot;Jane Doe&quot;,age:21}},{athlete:{name:&quot;Jack Doe&quot;,age:22}},{athlete:{name:&quot;Joe Doe&quot;,age:23}}]}};
const getPlayers = document.getElementById(&#39;getPlayers&#39;);

getPlayers.append(...data.team.roster.map(o =&gt; new Option(o.athlete.name)));

<!-- language: lang-html -->

&lt;select id=&quot;getPlayers&quot; data-category=&quot;Vote&quot; data-action=&quot;click&quot; data-label=&quot;Select Player&quot;&gt;
    &lt;option value=&quot;&quot;&gt;Select player&lt;/option&gt;
&lt;/select&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月13日 10:55:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76675598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定