如果第二个数组的项目包含数组的第一个对象的 id,则合并 Angular 8 中的两个对象数组
Posted
技术标签:
【中文标题】如果第二个数组的项目包含数组的第一个对象的 id,则合并 Angular 8 中的两个对象数组【英文标题】:Merge two array of objects in Angular 8 if the item of second array contains the id of the first object of array 【发布时间】:2019-11-10 18:23:41 【问题描述】:我正在尝试合并两个对象数组,其中第一个数组有一个 json 文件,第二个相同,但第二个包含第一个对象数组的 id。
我正在尝试将每个对象的第二个数组添加到第一个对象数组的正确项中。
如您所见,comments
有一个postId
,它知道它属于哪个帖子。
我的json
文件看起来像这样。
"posts": [
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
,
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla"
,
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure voluptatem occaecati omnis eligendi aut ad voluptatem doloribus vel accusantium quis pariatur molestiae porro eius odio et labore et velit aut"
,
"userId": 1,
"id": 4,
"title": "eum et est occaecati",
"body": "ullam et saepe reiciendis voluptatem adipisci sit amet autem assumenda provident rerum culpa quis hic commodi nesciunt rem tenetur doloremque ipsam iure quis sunt voluptatem rerum illo velit"
,
"userId": 1,
"id": 5,
"title": "nesciunt quas odio",
"body": "repudiandae veniam quaerat sunt sed alias aut fugiat sit autem sed est voluptatem omnis possimus esse voluptatibus quis est aut tenetur dolor neque"
,
和相同的json
,但用另一个API
来获取数据。
"comments": [
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos tempora quo necessitatibus dolor quam autem quasi reiciendis et nam sapiente accusantium"
,
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic@sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam et omnis occaecati quod ullam at voluptatem error expedita pariatur nihil sint nostrum voluptatem reiciendis et"
,
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Just@do.it",
"body": "consectetur cumque impedit blanditiis non eveniet odio maxime blanditiis amet eius quis tempora quia autem rem a provident perspiciatis quia"
,
"postId": 1,
"id": 4,
"name": "alias odio sit",
"email": "Just@do.it",
"body": "impedit nostrum id quia aut est fuga est inventore vel eligendi explicabo quis consectetur aut occaecati repellat id natus quo est ut blanditiis quia ut vel ut maiores ea"
,
"postId": 1,
"id": 5,
"name": "vero eaque aliquid doloribus et culpa",
"email": "Hayden@althea.biz",
"body": "harum non quasi et ratione tempore iure ex voluptates in ratione harum architecto fugit inventore cupiditate voluptates magni quo et"
,
"postId": 2,
"id": 6,
"name": "et fugit eligendi deleniti quidem qui sint nihil autem",
"email": "Presley.Mueller@myrl.com",
"body": "doloribus at sed quis culpa deserunt consectetur qui praesentium accusamus fugiat dicta voluptatem rerum ut voluptate autem voluptatem repellendus aspernatur dolorem in"
,
"postId": 2,
"id": 7,
"name": "repellat consequatur praesentium vel minus molestias voluptatum",
"email": "Just@do.it",
"body": "maiores sed dolores similique labore et inventore et quasi temporibus esse sunt id et eos voluptatem aliquam aliquid ratione corporis molestiae mollitia quia et magnam dolor"
,
我创建了一个模型和服务来定义数据和获取数据。
export class Post
userId: number;
id: number;
title: string;
body: string;
import Injectable from '@angular/core';
import HttpClient from '@angular/common/http';
import Observable from 'rxjs';
@Injectable(
providedIn: 'root'
)
export class PostService
private baseUrl = 'http://localhost:3000/posts';
constructor(private http: HttpClient)
getPost(id: number): Observable<any>
return this.http.get(`$this.baseUrl/$id`);
getPostsList(): Observable<any>
return this.http.get(`$this.baseUrl`);
deletePost(id: number): Observable<any>
return this.http.delete(`$this.baseUrl/$id`);
这是component
export class PostsListComponent implements OnInit
public posts: Observable<Post[]>;
constructor(private postsService: PostService)
ngOnInit()
this.comments$ = this.commentsService.getCommentsList();
this.posts = this.postsService.getPostsList();
this.groupedComments$ = this.comments$.pipe(
map(comments => lodash.groupBy(comments, 'postId'),
));
html 代码
<tr class="row" *ngFor="let post of posts | async">
<td class="col">post.title</td>
<td class="col-6">post.body</td>
<td class="col"><button (click)="deletePost(post.id)" class="btn btn-danger">Delete</button>
<button (click)="postDetails(post.id)" class="btn btn-info" style="margin-left: 10px">Details</button>
</td>
</tr>
【问题讨论】:
你能说出你期望的输出数组是什么吗? @AshishPatel 我希望我可以在一个数组中显示帖子和 cmets,然后例如哪些 cmets 属于哪个帖子。 【参考方案1】:我建议按 postId 对 cmets 进行分组,例如使用 lodash
this.groupedComments$ = this.comments$.pipe(
map(comments => lodash.groupBy(comments, 'postId')),
);
那么你就可以简单的在模板中访问这个对象了
<tr class="row" *ngFor="let post of posts | async">
<td class="col">post.title</td>
<td class="col-6">post.body</td>
<td class="col">
<div *ngFor="let comment of groupedComments[post.id]">comment</div>
</td>
<td class="col"><button (click)="deletePost(post.id)" class="btn btn-danger">Delete</button>
<button (click)="postDetails(post.id)" class="btn btn-info" style="margin-left: 10px">Details</button>
</td>
</tr>
(async-pipe groupedComments$ 之前的任何位置)
已编辑:
interface Comment
postId: number;
id: number;
name: string;
email: string;
body: string;
interface CommentGroup
[key: number]: Comment[];
comments$: Observable<Comments[]>;
groupedComments$: Observable<CommentGroup>;
【讨论】:
如您所定义的this.groupedComments$
和 this.comments$
comment$ 是您对 cmets 的可观察值,就像帖子一样。 groupedComments$ 是管道映射的结果
已添加,这是您想要的吗?
我遇到了一个错误。 ERROR TypeError: Cannot read property '1' of undefined
我不知道为什么我已经添加了你在代码中添加的所有内容。
也许你的 post-observable 在 cmets-observable 之前完成。请确保仅在两个 observables 完成时才显示数据以上是关于如果第二个数组的项目包含数组的第一个对象的 id,则合并 Angular 8 中的两个对象数组的主要内容,如果未能解决你的问题,请参考以下文章