简体   繁体   English

循环遍历对象

[英]Looping through object

I am doing an exercise using swapi co API, and after I fetched results from the website but I want to display only some of API objects.我正在使用 swapi co API 做一个练习,在我从网站获取结果后,但我只想显示一些 API 对象。 For the moment I am struggling with displaying all array spaceships.目前我正在努力展示所有阵列飞船。

var linkApi="https://swapi.co/api/starships"
async function starships() 
{
  let response = await fetch(linkApi);
  let data = await response.json()

 for(i=0; i<data.results.length;i++){
  return{

    "count": data.count,
    "results":[
        {
            "name":data.results[i].name,
            "model": data.results[i].model,
            "crew":data.results[i].crew,
        }
    ]

  }
}
  }


starships()
  .then(data => console.log(data));


this is the format that I want to achive这是我想要达到的格式

 {
  "count": "",
  "results": [
    {
      "name": "",
      "model": "",
      "crew": "",
      "passengers": "",
      "films_count": "",
      "films": [
        {
          "title": "",
          "director": "",
          "release_date": ""
        }
      ]
    }
  ]
}

The return will finish your function returning just the first spaceship info.返回将完成您的功能,仅返回第一个宇宙飞船信息。 You should create an object outside the for loop and after the for ends pass it an array with all the spaceships in the format you want您应该在 for 循环之外创建一个对象,并在 for 结束后将一个包含所有飞船的数组以您想要的格式传递给它

var linkApi="https://swapi.co/api/starships"
async function starships() 
{
    let response = await fetch(linkApi);
    let data = await response.json()
    let spaceshipsArray = [];
    let result = {
        "count": data.length
    };
    for(i=0; i < data.results.length;i++){

            spaceshipsArray.push({
            "name":data.results[i].name,
            "model": data.results[i].model,
            "crew":data.results[i].crew,
            });

    }
    }
    result.results = spaceshipsArray;
    return result;
  }

It would be something like that.它会是那样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM