Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 foreach object?

I have an Array of Objects called comments, and I'm trying to select only one's that have the id of post that I need to another array of objects. And the problem is that I can't find a way to copy the object I have found. This is my function:

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

Thank you.

like image 897
serj Avatar asked Aug 31 '16 17:08

serj


1 Answers

i guess you are looking for filter,

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

it will give you filtered array of comments based upon id.

Hope this helps!!

like image 54
Madhu Ranjan Avatar answered Sep 22 '22 08:09

Madhu Ranjan