Angular2 foreach object?

I have an array of objects called comments, and I'm trying to select only the one that has the message id that I need for another array of objects. And the problem is that I cannot find a way to copy the found object. This is my function:

comments = []; commentspart = []; private loadPartComments(id){ this.comments.forEach(element => { if (element.postId == id) { this.commentspart = ????; } }); return this.commentspart; } 

Thanks.

+5
source share
1 answer

I think you are looking for filter ,

  comments = []; commentspart = []; private loadPartComments(id){ this.commentspart = this.comments.filter(element => { return element.postId == id; }); } 

it will provide you with a filtered array of comments based on id.

Hope this helps!

+7
source

All Articles