按键/值合并对象数组

时间:2019-09-30 22:49:27

标签: javascript arrays api

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

例如,我有一个genre_id数组,如下所示:

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的显示对象添加一个新属性,该属性通过体裁响应获得体裁名称。

1 个答案:

答案 0 :(得分:1)

最好的选择是首先将您的流派转换为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(', ');
});