0

I want to merge two arrays of objects that I receive from a call to an API (https://developers.themoviedb.org/3/getting-started/introduction this one). I've created this simple function in methods to merge two arrays in Vue, but every time I obtain an empty array

mergeArrays(arr1, arr2) {
          let arrMerged = [...arr1, ...arr2];
          return arrMerged;
    }

So, I thought the problem was maybe the asynchronous call. So, to be sure the arrays were filled before return something, I put this if statement, but I don't obtain anything, the function doesn't start.

mergeArrays(arr1, arr2) {
          if (arr1.length == 19 && arr2.length == 16 ) {
              let arrMerged = [...arr1, ...arr2];
              return arrMerged;
          }
        }

The arrays are obtained this way:

 mounted () {
        // First Array
        // Obtaine movies genres and put them in an re-usable array 
        axios
            .get(`https://api.themoviedb.org/3/genre/movie/list`, {
                params: {
                            api_key: this.apiKey,
                            language: this.userLanguage,
                        },
            })
            .then((response) => {
                const genres = response.data.genres;
                genres.forEach(element => {
                    let genreId = element.id;
                    let genreName = element.name;
                    this.genresMovies.push( 
                        {
                            id: genreId, 
                            name: genreName
                        }
                    );
                });
            })

    // Second Array
    // Obtaine tv genres and put them in an re-usable array 
    axios
        .get(` https://api.themoviedb.org/3/genre/tv/list`, {
            params: {
                        api_key: this.apiKey,
                        language: this.userLanguage,
                    },
        })
        .then((response) => {
            const genres = response.data.genres;
            genres.forEach(element => {
                let genreObj = element;
                let genreId = element.id;
                let genreName = element.name;
                        this.genresTV.push( 
                        {
                            id: genreId, 
                            name: genreName
                        }
                    );
            });
        })

this.genresTV and this.genresMovies are empty array defined in data and filled here. Once filled they appear this way:

Array 1

0:
id: 28
name: "Azione"

1:
id: 12
name: "Avventura"

2:
id: 16
name: "Animazione"

3:
id: 35
name: "Commedia"

4:
id: 80
name: "Crime"

5:
id: 99
name: "Documentario"

6:
id: 18
name: "Dramma"

7:
id: 10751
name: "Famiglia"

8:
id: 14
name: "Fantasy"

9:
id: 36
name: "Storia"

10:
id: 27
name: "Horror"

11:
id: 10402
name: "Musica"

12:
id: 9648
name: "Mistero"

13:
id: 10749
name: "Romance"

14:
id: 878
name: "Fantascienza"

15:
id: 10770
name: "televisione film"

16:
id: 53
name: "Thriller"

17:
id: 10752
name: "Guerra"

18:
id: 37
name: "Western"


Array 2

0:
id: 10759
name: "Action & Adventure"

1:
id: 16
name: "Animazione"

2:
id: 35
name: "Commedia"

3:
id: 80
name: "Crime"

4:
id: 99
name: "Documentario"

5:
id: 18
name: "Dramma"

6:
id: 10751
name: "Famiglia"

7:
id: 10762
name: "Kids"

8:
id: 9648
name: "Mistero"

9:
id: 10763
name: "News"

10:
id: 10764
name: "Reality"

11:
id: 10765
name: "Sci-Fi & Fantasy"

12:
id: 10766
name: "Soap"

13:
id: 10767
name: "Talk"

14:
id: 10768
name: "War & Politics"

15:
id: 37
name: "Western"

I call the function this way in mounted after the second axios

const arr = this.mergeArrays(this.genresMovies, this.genresTV);

I can't figure out what's wrong

Alebacce
  • 63
  • 12
  • try with something simpler: `this.mergeArrays([1,2,3], [4,5,6]);` – Alberto Sinigaglia May 05 '21 at 17:16
  • and check if it's working, if it is, the problem is somewhere else, otherwise you probably have some kind of broken SDK, because it should work – Alberto Sinigaglia May 05 '21 at 17:17
  • 2
    Please provide more code to reproduce this. See [mcve] – T J May 05 '21 at 17:21
  • @Berto99 tried your solution, it gives me back undefined, and that's very strange – Alebacce May 05 '21 at 17:28
  • @Alebacce are you sure that (1) you are returning the array (2) you are outputting the actual returned value? (btw, take out that if) – Alberto Sinigaglia May 05 '21 at 17:29
  • @HereticMonkey thanks for the link, I know very well in the last two day that page, unfortunately none of the solutions seen there work in my code – Alebacce May 05 '21 at 17:30
  • @Berto99 My bad , I forgot the if inside, now works fine – Alebacce May 05 '21 at 17:31
  • @Alebacce then the error is somewhere else, you are not probably awaiting the results – Alberto Sinigaglia May 05 '21 at 17:31
  • I updated my question with more, I hope, useful information, I think there's everything needed. – Alebacce May 05 '21 at 17:38
  • @Berto99 exactly what I thought, that's why I put that if inside, even if maybe it's wrong. What I need so is to verify results are arrived correctly and then merge the two arrays, how is possible to do this thing if my way with the if in the function is wrong? – Alebacce May 05 '21 at 17:40
  • 1
    Learn how to use promises and async/await. Your problem is that at the point where you merge the arrays, the arrays are empty and have not been populated by the XHR responses. – Terry May 05 '21 at 17:49
  • 1
    The problem is you're merging the arrays before they are populated. With Vue, you don't even need to worry about that. You can use a computed property: `computed: { mergedArray() { return [...this.arr1, ...this.arr2] }}` and then all you have to do is populate the original arrays. The computed will update automatically. See it working [here](https://codesandbox.io/s/hidden-pond-jviug?file=/src/App.vue). I've also added a computed which removes duplicates based on `id`, since you'll likely want it. – tao May 05 '21 at 18:22
  • @tao To begin, sorry for the late response, but due to work I could text back only now. I've seen your code and it's awesome, really thanks even for the removal of the duplicates, really helpful and with a visible example it is even more. I've tried your solutions and console says "this.genresMovie is not iterable at wn.mergedArray". I've seen now that it's a common problem of objects and I have to do a for of loop. After this I think it should work as in your code – Alebacce May 06 '21 at 21:29

1 Answers1

0

This should work:

const arr = this.genresMovies.concat(this.genresTV);
Zniets
  • 33
  • 7