我有一个对象,其中一个属性是一个对象数组,想法是如果满足条件,将对象从该数组移动到新的数组中。
public $onInit(): void {
this.getTicket();
}
public ticket: any; // Object with the array
public comments: any = []; // New array to move the elements
public getTicket(): void {
this.ticketService
.getTicketComplete(this.$stateParams.ticketID)
.then((response: any) => {
this.ticket = response;
this.stringToDate(this.ticket);
this.ticket.messages.forEach((elem, index) => {
if (elem.type === "comment") {
this.ticket.messages.splice(index, 1);
this.comments.push(elem);
}
});
console.log(this.ticket);
});
}
我遇到的问题是这样的: 数组中有两种对象,消息和评论。如果数组中有2个消息和3个评论,则应将3个评论推送到新数组中并留下2个消息,但实际上只移动了2个评论。
有什么想法吗?谢谢您的帮助。
forEach
循环内修改了array
数组? - Arg0nfilter()
方法来过滤你想要在comments
对象中删除的元素类型,这应该是在你已经插入元素之后进行的。 - Alex Beugnetarray
中的元素并将其从数组中删除,然后将其推入新的数组...除了forEach
循环之外,还有其他方法可以实现吗? - Miguel Frias