簡體   English   中英

比較 object 的兩個 arrays 具有相同的值,並在 Vue.js2 中將一個數組的屬性轉換/添加到另一個數組

[英]Compare two arrays of object with same values and chenge/add a property of one array to the other one in Vue.js2

我有一個從 API ( https://developers.themoviedb.org/3/getting-started/introduction this one) 中獲取的對象數組,這些對象鏈接到一個變量,該變量是inputv-model 因此,每當變量更改時,數組也會隨着 @keyup 時調用 API 的@keyup 它有這樣的結構:

(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, __ob__: we]
0:
backdrop_path: "/pLG4ihU1d2XkQbASQDjsFu9U7d9.jpg"
first_air_date: "2021-03-24"
genre_ids: Array(3)
0: 18
1: 80
2: 9648
length: 3
__ob__: we {value: Array(3), dep: ce, vmCount: 0}
__proto__: Array
id: 120168
media_type: "tv"
name: "Che fine ha fatto Sara?"
origin_country: Array(1)
original_language: "es"
original_name: "¿Quién mató a Sara?"
overview: "Determinato a vendicarsi e a provare di essere stato incastrato per l'omicidio della sorella, Álex cerca di scoprire molto più del vero colpevole del crimine."
popularity: 529.698
poster_path: "/jnit57q25N5VvVrK4pj4Uj8BLe7.jpg"
vote_average: 7.8
vote_count: 430

這個數組為我提供了有關電影和電視劇的有用信息,但它並沒有給我返回類型,至少不是這些類型的名稱,而是與它們相關的 id 是的。 現在,我調用了另一個 API,它提供了這樣的流派列表:

(19) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
id: 28
name: "Azione"
__proto__: Object
1:
id: 12
name: "Avventura"
__proto__: Object
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"}
length: 19
__proto__: Array(0)

在這個數組內部,每個 object 的流派 ID 與genre-ids子數組中的前一個數組相同。 所以在我的邏輯中,如果這個子數組中的流派 ID 等於這個流派列表數組中的一個 ID,它也采用流派的名稱。 我正在使用 Vue 2。如何比較 arrays,檢查第一個數組的流派 ID 是否與第二個數組中包含的 ID 匹配,然后將流派的名稱添加到第一個數組的 object 中,以便我可以打印它們在 HTML 中?

這是一個可能且簡短的解決方案,可以為您提供一個想法:

const movies = [{genre_ids: [1,2]}, {genre_ids: [2]}, {genre_ids: [1,3]}];
const genres = [{id: 1, name: "genre1"}, {id: 2, name: "genre2"}, {id: 3, name: "genre3"}];
const moviesWithGenres = movies.map(movie => ({
    ...movie,
    genres: genres.filter(({ id }) => movie.genre_ids.includes(id))
  }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM