【问题标题】:Merge array of objects by key/value按键/值合并对象数组
【发布时间】:2019-09-30 22:49:27
【问题描述】:

我正在尝试找出将多维数组中的对象 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 的节目对象添加一个新属性,该属性通过流派响应获取流派名称。

【问题讨论】:

  • 给定两个输入“genre_ids”和“tv_show_genre_ids”,预期输出是多少?我认为这将有助于更好地理解问题。
  • 每个节目对象都有一个包含流派ID数组的属性。我希望该数组中的每个值都映射到我已经拥有的流派列表数组中的值,然后为每个单独的节目添加一个新属性,其中包含适用于它的所有流派名称。如果这有意义吗?您可以看到我创建的新属性“show.genre_names”。我希望它包含所有流派名称,但我需要通过它在另一个数组中的 ID 来获取流派的名称。
  • 我的意思是,你能给出实际的输出吗?不是解释。如果您通过控制台记录输出以获取示例输入,会是什么样子?
  • 我已对原始帖子进行了编辑。我希望这是您在输入方面所要求的。对不起,如果我误解了你的问题。

标签: javascript arrays api


【解决方案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(', ');
});

【讨论】:

  • 谢谢,这看起来更干净了:-)
猜你喜欢
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 2017-02-25
  • 2019-09-04
  • 2011-04-04
相关资源
最近更新 更多