Traversing an object with a loop

I'm currently working on a project that involves utilizing the swapi co API. Although I've successfully fetched results from the website, I'm struggling with displaying only specific API objects, particularly 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 desired format:

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

Answer №1

After looping through the spaceship data, you should create an object to store all the information in the desired format. This object will be returned at the end of the function with details of the first spaceship only.

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;
  }

This setup will allow you to properly structure and return the spaceship data as needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating Object of Objects in TypeScript: A Comprehensive Guide

Assuming I have a structure similar to this: interface Student { firstName: string; lastName: string; year: number; id: number; } If I intend to handle an array of these structures, I can simply specify the type as Student[]. Instead of utilizin ...

Error occurs with Nodemon application crashing while executing Gulp command

Recently, my React app started crashing whenever I run the Gulp command. Oddly enough, it was functioning perfectly just a few hours ago. The only change I made was updating my node version from 6.2.1 to 6.2.2 in order to deploy the application on Azure. H ...

Various tasks to be executed on a shared element

Struggling with implementing actions on a grid component without using a router in Next.js. Here is the current code snippet: const handleActions = (btnPress, row) => { if (btnPress === "Add") {/* implementation */} else if (btnPr ...

Building a contact form in Angular and sending emails with Nodemailer

Currently, I am in the process of setting up a contact form for my website. Since I am utilizing a MEAN stack, it made sense to incorporate the nodemailer module for sending emails. In order to handle this functionality, I have established an endpoint &ap ...

How can one properly iterate through an HTML Collection in JavaScript?

I need help with creating a slider using JavaScript. The code I have written below calculates the widths of the slides, but it's throwing an error in the console. Can someone advise on how to properly loop through and assign width to these elements? ...

File bootstrap.min.css is currently experiencing compatibility issues

I am currently working on a website where I have two images that are displaying vertically. However, I would like these images to be displayed horizontally with animation. I attempted to use Bootstrap to achieve this horizontal layout, but when I include ...

Unable to retrieve data from JSON

Advice needed on how to access an API using PHP. Click here. $json = file_get_contents("http://market.huobi.com/staticmarket/detail.html"); $obj = json_decode($json); See a snippet of the API response below. $obj = { "sells": [ { ...

Import a precise model from a glb file

Greetings! I am relatively new to working with ThreeJS and just getting the hang of it. After going through some tutorials, I have successfully managed to load glb files and render them in my browser with ease. Recently, I downloaded a GLB file from that ...

Complete loading of iframe content on Internet Explorer versions 8 and 9

Having an issue with the full loading of a page in IE8-9. I need to perform certain actions after the content within a div is fully loaded, but it seems that in IE8-9, the page fails to load completely. This is causing problems as my actions are dependent ...

Error: The function window.intlTelInput is not recognized within the ReactJS framework

I am currently learning ReactJS and encountering an issue when using jQuery with React JS for intlTelInput. I have installed npm jQuery and imported all the necessary code. Additionally, I have included all the required CSS and jQuery links in my index.htm ...

Asynchronous retrieval of reference value from Firebase Firestore in ReactJS

Encountering a peculiar bug in TypeScript-JavaScript where I have a Model class in TypeScript and a ReactJS Component in JS. The issue arises when dealing with a list of Promo Objects, each containing a "_listCompte" property which holds a list of Compte O ...

The React apexchart heatmap's height remains static despite attempting to change it through state updates

Seeking to dynamically resize the height of an "Apexcharts heatmap" based on server data. Despite attempting to manipulate code in various lifecycle methods, including componentDidMount() and where the data is received, I have not been successful. Within ...

I am interested in discovering the optimal method for loading a vehicle to its maximum capacity by exploring various combinations

My current task involves developing an algorithm to optimize the filling of a vehicle to its capacity based on various input combinations. Although the core problem has been resolved, the algorithm's efficiency is inadequate when dealing with a higher ...

Change the format of the array from the initial array to the new array structure

I have a multi dimensional array that I need to convert into the array2 structure. I've tried various methods, but all of them have resulted in bulky code and lots of iteration. Is there an easier way to accomplish this task? I am new to Angular and ...

Building numerous pagination features in a single page using Codeigniter

I'm just starting out with codeigniter and I need help creating multiple paginations on one page. I've tried it, but only one pagination is working while the others are giving me errors. Can someone please assist me? I read some suggestions that ...

Utilize Jquery to extract the functions from a PHP file

I'm a beginner with both jQuery and PHP. Currently, I have an HTML page where I need to utilize functions from a PHP file using jQuery, and then display the results in the HTML. My goal is to count the number of files in three different directories a ...

My simple application is experiencing a problem where ComponentDidMount is not being invoked

I used a tool called create-react-app to build this simple application. Strangely, the ComponentDidMount method is never getting invoked. import React, { Component } from "react"; class App extends Component { componentDidMount() { console.log("M ...

Adapting Classes in Javascript Based on Screen Width: A Step-by-Step Guide

I'm dealing with two separate menus - one for mobile version and one for PC version. However, the mobile menu seems to be overlapping/blocking the PC menu. How can I resolve this issue? I've attempted various solutions such as removing the mobil ...

What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows: { "status": "success", "response": [ { "id": 1, "name": "SEA BUSES", "image": null }, { "id": 2, ...

What are the specific extensions for email validation?

code for the form: <form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" > <p class="email"> <label for="budget">Expected Budget ...