【发布时间】:2019-10-29 07:39:39
【问题描述】:
我从 API 调用中获取数据。我有一个多对多的关系 - 我将与人们解释它的电影。一部电影有很多人看,一个人可以看很多部电影。 所以在 Angular 前端,当你点击一个人时,你应该得到这个人的更详细的视图,包括他看过的电影列表。
当我运行这段代码时(person-detail.component.ts):
public selectedperson: any = []
/*Array that contains data from the selected person*/
public movie: any = []
/*Array that contains all the movie-person connections (movie-name and person_id)*/
public selectedmovie: any = []
/*array that should contain all the movies the selectedperson has watched*/
/*some code*/
getMovies(){
const url ='http://localhost:4000/api/people-movies';
this.http.get(url).subscribe(movie => {
this.movie = movie;
this.selectedmovie=this.movie.find(item=>
{
for (var i = 0; i < this.movie.arrayLength; i++) {
if(item['person_id']===this.selectedperson.person_id)
{
return true;
}
return false;
}
});
console.log(this.selectedmovie, this.selectedperson.person_id);
return this.selectedmovie;
});
}
它不起作用 - 但没有这个循环(如果我离开 If 语句):
for (var i = 0; i < this.movie.arrayLength; i++) {
}
它只返回此人的一部电影 - 因此它一找到电影就停止。但是因为我想列出所有电影,所以我需要循环。
那么我在循环中做错了什么?
编辑: selectedperson 中的示例数据(已填写): 选定的人:
[{"person_id"=34, "name"="john"}]
movie(使用提到的 URL 从 API 调用中获取此数据):
[{"person_id"=33, "movie"="Titanic"}{"person_id"=33, "movie"="Star Wars"}{"person_id"=34, "movie"="Titanic"}{"person_id"=34, "movie"="Star Wars"}{"person_id"=34, "movie"="Indiana Jones"}{"person_id"=35, "movie"="Titanic"}]
想要的最终结果(对于 id 为 34 的人)
Titanic
Star Wars
Indiana Jones
【问题讨论】:
-
我真的不明白你在做什么。您正在尝试填充
selectedmovie- 这是一个空数组- 通过激活自身的find函数... -
你能写下你的样本数据和想要的结果吗?
selectedmovie、movie和selectedperson的数组? -
另外,你正在创建一个
for循环,但不要在内部的任何位置使用i...那有什么意义呢? -
如果您想获取所有符合特定条件的元素,请使用过滤器。 find 只返回第一个匹配项
-
@butterfly 基本上,在
for循环中,您执行此item['person_id']===this.selectedperson.person_id比较X 次(根据movie长度),但item不变,this.selectedperson.person_id也不变。所以它在同一部电影上一遍又一遍地使用相同的兼容性。
标签: javascript arrays json angular loops