2017-08-28 197 views
1

我有一个对象,其中一个属性是对象数组,如果一个条件为真,则想法是将对象从该数组移动到不新对象。将对象从一个阵列移动到另一个阵列

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条评论。

任何想法。谢谢你的帮助。

+3

也许原因是你修改'forEach'环内的'array'? – Arg0n

+1

你应该使用'filter()'方法来过滤哪些类型的元素你想要删除** **你已经在你的'comments'对象中插入了你的元素 –

+0

是的想法是循环'数组'寻找元素,并从数组中删除元素,并将其推入一个新的....是否有任何方法可以做到'forEach'循环之外....? –

回答

2

这是做到这一点:

var array1 = [1, 2, 3, 4, 5]; 
 
var array2 = []; 
 

 
array1.forEach(function(elem, index) { 
 
    array1.splice(index, 1); 
 
    array2.push(elem); 
 
}); 
 

 
console.log(array1); //[2, 4] 
 
console.log(array2); //[1, 3, 5]

这是它如何工作的一个示例:

var array1 = [1, 2, 3, 4, 5]; 
 
var array2 = []; 
 

 
for(var i = 0; i < array1.length; i++) { 
 
    array2.push(array1[i]); 
 
    array1.splice(i, 1); 
 
    i--; //decrement i IF we remove an item 
 
} 
 

 
console.log(array1); //[] 
 
console.log(array2); //[1, 2, 3, 4, 5]

具体使用情况为您提供:

let messages = this.ticket.messages; 
for(let i = 0; i < messages.length; i++) { 
    let message = messages[i]; 
    if (message.type === "comment") { 
    this.comments.push(message); 
    messages.splice(i, 1); 
    i--; 
    } 
} 
+0

即使先推送元素,然后移除它仍然留下一个注释,然后其余的都推入新的数组。 –

+0

查看更新的答案,以便用(for'-loop)替换你的'forEach'循环。你的问题不是当你推动元素时,而是现在数组中少了1个元素。而且你不能以我知道的任何方式在'forEach'循环中递减'index'。 – Arg0n

+0

感谢问题的答案,我很高兴知道我无法使用forEach减少索引,感谢您的帮助,并感谢其他人员如何给出创意。 –

0

当您循环访问数组时,您正在删除元素 - 这绝不是一个好主意。解决此问题的更好方法是先将它们添加到this.comments中,然后在foreach完成时,开始循环this.comments并从消息中删除此数组中的那些。