javascript - 按键/值合并对象数组

标签 javascript arrays api

我试图找出将多维数组中的对象 id 属性映射到共享相同 id 的另一个数组中的对象值的最佳方法。

举个例子,我有一个像这样的genre_ids数组:

0: {id: 1, name: 'sci-fi'},
1: {id: 2, name 'comedy'},
2: {id: 3, name: 'action'}

还有一个 tv_show_genre_ids 数组,如下所示:

0: {name: ..., genre_ids: [1, 4, 9]},
1: {name: ..., genre_ids: [2, 3, 4]},

我试图找出通过 ID 检索流派名称列表的最佳方法。

到目前为止,我已经成功创建了一个工作解决方案,但感觉非常脏,因为我正在执行多个嵌套循环,并且我不确定是否有更干净、更具声明性的方法来解决我的解决方案

这是我的方法,假设我已经有一个流派 ID 和名称列表(在 this.genres 中访问。

this.http.get('https://api.com/shows')
    .subscribe((res: array <any> ) => {
        this.shows = res.results;
        this.shows.forEach(show => {
            show.genre_names = '';
            show.genre_ids.forEach(id => {
                for (const [i, v] of this.genres.entries()) {
                    if (id == v.id) {
                        if (this.genres[i] && this.genres[i].name) {
                            if (show.genre_names === '') {
                                show.genre_names = this.genres[i].name
                            } else {
                                show.genre_names += `, ${this.genres[i].name}`;
                            }
                        }
                    }
                }
            })
        });
    });

有没有更好的方法来做到这一点,因为当我尝试将多维数组中的一个对象的 id 映射到另一个对象时,我似乎经常遇到这种类型的问题。

任何指导将不胜感激。

编辑:

以下是来自 API af 的流派数据示例:

 0: {id: 10759, name: "Action & Adventure"}
 1: {id: 16, name: "Animation"}

以下是来自 API 的显示数据示例:

0:
backdrop_path: "/ok1YiumqOCYzUmuTktnupOQOvV5.jpg"
first_air_date: "2004-05-10"
genre_ids: (2) [16, 35]
id: 100
name: "I Am Not an Animal"
origin_country: ["GB"]
original_language: "en"
original_name: "I Am Not an Animal"
overview: "I Am Not An Animal is an animated comedy series about the only six talking animals in the world, whose cosseted existence in a vivisection unit is turned upside down when they are liberated by animal rights activists."
popularity: 10.709
poster_path: "/nMhv6jG5dtLdW7rgguYWvpbk0YN.jpg"
vote_average: 9.5
vote_count: 341 

我想向名为 Genre_names 的节目对象添加一个新属性,该属性通过流派响应获取流派名称。

最佳答案

最好的办法是首先将您的流派转换为 Map 或用作查找的对象:

const genreLookup = new Map();
this.genres.forEach(genre => genreLookup.set(genre.id, genre));

现在,当您处理一系列节目时,您不必多次循环播放流派:

this.shows.forEach(show => {
  show.genre_names = show.genre_ids
    .filter(id => genreLookup.has(id))
    .map(id => genreLookup.get(id).name)
    .join(', ');
});

关于javascript - 按键/值合并对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58176156/

相关文章:

javascript 代数求解 x

javascript - 使用 id 获取主干集合中的问题

javascript - 如何显示数组中的图像? JavaScript

java - 改变Java中数组的大小

api - 对于使用 Jenkins API 创建作业的脚本,Jenkins 用户身份验证详细信息如何为 "passed"?

api - 如何将切片器值设置为Power BI中第一个可用值表单表?

javascript - 如何通过 ajax 动态加载 list.js 并使排序继续工作

c++ - 不准确的 C++ 阶乘程序

api - Webkit音频Api createMediaElement源

javascript - 在鼠标悬停时显示一个 div,类似于 Google Chrome WebStore 磁贴