Home > Mobile >  How to delete attachment from the attachment object array inside another comment object array which
How to delete attachment from the attachment object array inside another comment object array which

Time:01-10

I would like to remove an attachment from the array of attachment objects which is inside another array of comment objects which is inside of another object array. I have been struggling with the solution.

export class CommentSection{
  id: string;
  comments: CommentObject[];
}
export class CommentObject{
  id: string;
  created: Date;
  text: string;
  attachments: CommentAttachment[];
}
export class CommentAttachment{
  id: string;
  created: Date;
  filename: string;
}

And my ts file with draft solution, which is not working (not deleting attachment):

export class CommentsComponent {

  public comment: CommentObject;
  commentsArray: CommentSection;

  public deleteCommentAttachment(attachment: CommentAttachment): void {
    this.commentsArray.comments = this.commentsArray.comments.filter((c) =>
      c[this.comment.id].attachments.splice(attachment.id, 1),
    );
  }
}

CodePudding user response:

You may also transform into rxjs to do it in readable steps, although some may find it as overkill. Here is the example:

https://stackblitz.com/edit/angular-ivy-swnhf1?file=src/app/app.component.ts

CodePudding user response:

You want to filter the attachments not the comments right? Also splice is working with indexes not custom id-s. Ive replaced filter with map. Have not tested it but it should work:)

this.commentsArray.comments = this.commentsArray.comments.map((c) => {
    const comment = c[this.comment.id];
    const attachments = comment.attachments;
    const index = attachments.findIndex(at => at.id == attachment.id);
    attachments.splice(index, 1);
  });
  •  Tags:  
  • Related