Angular 2 - 将函数应用于数组

时间:2017-04-24 16:30:12

标签: javascript arrays angular typescript

我有一个“any”类型的数组,里面有多个对象,如下所示:

//List of posts (array)
this.posts = [

       //First Post (object)
       {
            userFirst: 'Teyah',
            userLast: 'Tharpe',
            postText: 'Good morning, everyone! Have a good day. :)',

            //First Post's comments (array)
            comments: [
                //First Comment (object)
                {
                    cFirstName: 'Jalen',
                    cLastName: 'Tharpe',
                    theirComment: 'Thank you'
                },

                //Second Comment (object)
                {
                    cFirstName: 'Gerald',
                    cLastName: 'Matthews',
                    theirComment: 'Thank you! You do the same.'
                }
            ]
        },

        //Second Post (object)
        {
            userFirst: 'Jordan',
            userLast: 'Gibson',
            postText: 'What is the move for today?',
            comments: [
                {
                    cFirstName: 'Joshua',
                    cLastName: 'Stewart',
                    theirComment: 'Party at my house!!!'
                }
            ]
        }

    ];

如您所见,我有一系列帖子,其中包含对象,在帖子对象中,我有一个评论列表。我正在尝试将comment()函数应用于其中一个对象。说,posts[0]。如果这是在Angular 2的范围内,有人可以告诉我吗?如果是这样,请帮助。

如果需要更多代码/信息,请告知我们。

谢谢。

1 个答案:

答案 0 :(得分:0)

Yes, this is within the scope of Angular, as it is in the scope of javascript! The detailed answer to your question depends on exactly what you want to do with your comment() function. I will try to anticipate a couple of things you might like to do.

  1. Add a new comment to a certain post's comment array

    addComment(post, comment) {
      post.comments.push(comment);
    }
    
  2. Find a post based on its index and add a comment

    addCommentUsingIndex(postIndex, comment) {
      this.posts[postIndex].comments.push(comment);
    }
    
  3. Extract the number of comments for a given post

    countComments(postIndex) {
      return this.posts[postIndex].comments.length;
    }
    
  4. get an array of the full names of each commenter of a certain post

    transformComments(postIndex) {
      return this.posts[postIndex].comments.map(comment => {
        return comment.cFirstName + ' ' + comment.cLastName
      });
    }
    

Does that roughly cover your requirements?