koko
koko

Reputation: 19

How do I assign an array to another array?

Here is my code

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 = [];

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

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

          //push 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 need help assigning the planetData array to this.data{}. I tried the following this.data{ planets: [planetData], but it gave an error "Cannot access 'planetData' before initialization", which was expected. My syntax is also probably wrong, but I'm really new to JS.

Upvotes: 0

Views: 509

Answers (2)

nullromo
nullromo

Reputation: 2637

You should assign the variable after the planetData array has been populated.

Perhaps you can try something like this:

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

Upvotes: 2

George Sun
George Sun

Reputation: 1080

You can assign planetData to the key planets later in your code using:

this.data.planets = planetData;

Upvotes: 1

Related Questions