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