【问题标题】:Compare two arrays of object with same values and chenge/add a property of one array to the other one in Vue.js2比较两个具有相同值的对象数组,并在 Vue.js2 中将一个数组的属性转换/添加到另一个数组
【发布时间】:2021-07-24 19:05:49
【问题描述】:

我有一个从 API(https://developers.themoviedb.org/3/getting-started/introduction 这个)获取的对象数组,它链接到一个变量,该变量是 inputv-model。因此,每当变量更改时,数组也会随着@keyup 时调用 API 的函数而更改。 它的结构如下:

(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)

在这个数组中,每个对象都具有与genre-ids 子数组中的前一个数组相同的流派ID。所以在我的逻辑中,如果这个子数组中的流派 ID 等于这个流派列表数组中的一个 ID,它也采用流派的名称。我正在使用 Vue 2。 如何比较两个数组,检查第一个数组的流派 ID 是否与第二个数组中包含的 ID 匹配,然后将流派的名称添加到第一个数组的对象中,以便我可以在 HTML 中打印它们?

【问题讨论】:

  • 我建议您使用array1.map 这样您就可以访问第一个数组中的每个单独元素(对象),并通过循环将其与第二个数组中的对象进行比较,如果它们在任何时候匹配,你从第二个数组中抓取对象,将它包含在第一个数组的对象中
  • 谢谢,我试试!我不知道你可以匹配单个元素,但它毕竟是一个数组

标签: javascript arrays vue.js object vuejs2


【解决方案1】:

这是一个可能的简短解决方案,可以为您提供一个想法:

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))
  }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-04
    • 2021-12-04
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多