What is the process for assigning one array to another array in programming?

Check out this code snippet:

export default class Application extends EventEmitter {
  constructor() {
    super();

    this.config = config;
    this.data = {
      planets: [planetData]
    };

    this.init();

    let url;
    let count;
    let planetData = []
    let promises = [];

    //Loop through multiple pages
    for (let p = 1; p < 7; p++) {
      url = `https://swapi.boom.dev/api/planets?page=${p}`;

      //Fetch data from API
      promises.push(fetch(url).then(res => res.json())
        .then(data => {

          //Append fetched data to array
          for (let i = 0; i < data.results.length; i++) {
            planetData = planetData.concat(data.results[i]);
          }

        }));
    }

    Promise.all(promises)
      .then(() => {
        console.log(planetData.length, '=>', planetData);
      })
  }

I'm struggling with assigning the planetData array to this.data{}. I attempted using this.data{ planets: [planetData], but it resulted in an error message "Cannot access 'planetData' before initialization" as anticipated. It's likely that my syntax is incorrect, but I'm very new to JavaScript.

Answer №1

Ensure to set the variable after all the values in the planetData array have been added.

Here is a possible solution:

Promise.all(promises)
    .then(() => {
      console.log(planetData.length, '=>', planetData);
    })
    .then(() => {
        this.data.planets = planetData;
    })

Answer №2

Incorporate the variable planetData into the value associated with the key planets at a later point in your script by utilizing this syntax:

this.data.planets = planetData;

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

Track the status of an extensive MySQL query using PHP

Looking for a way to show the progress percentage of a lengthy mysql query using php? Well, you can create a filter button in your database that triggers a javascript function through ajax and calls a php file. function show(){ $.ajax({ ...

What is the best way to transfer an imageUrl from document data to a component within Astro.js?

Currently, I am immersed in a project involving Astro.js and facing the challenge of transferring the imageUrl data from the document to a MarkdownContainer component. The markdown template specifies the layout for Astro to utilize "../../layouts/Markdown ...

What could be causing localstorage to malfunction in Firefox 57 and Vuejs2?

I am looking to implement language change functionality in my application by clicking on the language name. I am currently using vuex-i18n to manage the language settings in the frontend. However, I have encountered an issue with localStorage not functioni ...

How to effectively handle multiple rows with numerous jQuery functions?

Here is a link to see my code in action: Example of my code working You can also check out another example with an ID here: Example 2 of my code I gave it another shot over at this link: http://jsbin.com/wazeba/edit?js,console,output And finally, one mo ...

What is the best way to integrate Emotion styled components with TypeScript in a React project?

Currently, I am delving into TypeScript and attempting to convert a small project that utilizes Emotion to TypeScript. I have hit a roadblock at this juncture. The code snippet below export const Title = styled.div(props => ({ fontSize: "20px", ...

Utilizing Jquery to apply CSS styles to three div elements sequentially with a timed loop of N seconds for each

I have 3 different HTML divs as shown below: HTML <div id="one" class="hide">Text one</div> <div id="two" >Text two</div> <div id="three" class="hide">Text three</div> I am looking to use jQuery to dynamically change ...

Is it possible for invoking a web service recursively in JavaScript to lead to a stack overflow issue

I am currently working on a migration procedure that may last between 2 to 3 days to complete. My concern is that the implementation I have in place could potentially result in a StackOverflow exception due to its recursive nature. I am questioning wheth ...

When utilizing image.width in JavaScript, it returns 0 exclusively when accessed online, but functions correctly when

Recently, I encountered a problem while rendering an image in React. I was using JavaScript to set the image width and applying it to the img style. let img = new Image(); img.src = "image_url"; let i_width = (img.width * 2.54) / 30; <img sr ...

Operating on JSON objects/arrays according to their values

I am working on developing a function that accepts a string as its first argument and a JSON LIST as its second argument: [ { "date": "09/09/18", "how_many": 11, "species": "XXXXX" }, { "date": "04/11/17", ...

Is it possible to utilize AJAX and JavaScript independently of a web browser?

For my project, I need to create a Java-Swing desktop application that will communicate with a server remotely through sockets, similar to Skype. Can AJAX be used to transfer the data to the server in this case? What is the best way to implement the JavaSc ...

Is it possible to generate a DenseMatrix in Scala Breeze comprised of elements that are arrays of integers?

Just came across Scala Breeze, a powerful linear algebra library designed for Scala applications. I'm curious to know if there's a way to initialize a DenseMatrix using an array of integers as its elements. Currently, I'm looking to transi ...

Passing an extra variable to the callback function in AJAX and saving the XMLHttpRequest.response as a variable

Attempting to read a local file on the server using the standard loadDoc(url, cfunc) function, my goal is to: 1) Search for a specific string in the file (getLine()); 2) If possible, save that line to a variable. For point 1, I provide a string to the c ...

Is there a simple method to automatically increase the version number of Mongoose documents with each update request?

I'm eager to utilize Mongooses document versioning feature with the "__v" key. Initially, I struggled with incrementing the version value until I learned that adding this.increment() when executing a query is necessary. Is there a method to have this ...

Using Browserify on files that have already been browserified

When trying to use browserify to require an already browserified module, I am running into an issue where the bundle cannot resolve the module that has already been browserified. For instance, I have a file called bundle-1.js that was bundled using the co ...

A solitary outcome yielded by the JSON iteration

Can anyone help me understand why this code is only returning 1 result instead of 4? I am trying to retrieve all the post titles in the category with ID 121, but it seems to only display the most recent post title. <script type="text/javascript> ...

Run a Javascript function when the expected event fails to happen

I currently have this setup: <input type="text" name="field1" onblur="numericField(this);" /> However, I am struggling to figure out how to execute the numericField() function for the element before the form is submitted. I attempted using document ...

The redirect feature in getServerSideProps may not function properly across all pages

Whenever a user visits any page without a token, I want them to be redirected to the /login page. In my _app.js file, I included the following code: export const getServerSideProps = async () => { return { props: {}, redirect: { des ...

"I'm experiencing an issue where my JSON data is not displaying in the browser when I run the code

I am having trouble displaying my json data in the browser. This is my first time working with json and I can't seem to identify the issue. I tried researching online and found that it could be related to mime types, but I still can't solve it. B ...

Error message in Typescript: "Property cannot be assigned to because it is immutable, despite not being designated as read-only"

Here is the code snippet I am working with: type SetupProps = { defaults: string; } export class Setup extends React.Component<SetupProps, SetupState> { constructor(props: any) { super(props); this.props.defaults = "Whatever ...

How is a byte array in C# affected when passed to unmanaged code within a struct?

Currently, I am in the process of developing a .NET DLL to interact with a C++ library that has been provided to me. Within the C++ library, there exists a struct defined as follows: typedef struct FOO { DWORD DataSize; BYTE *pData; } To replica ...