Mig*_*ias 3 javascript fuse typescript angular
我有一个对象,其中一个属性是一个对象数组,想法是如果一个条件为真,将对象从该数组移动到没有新对象.
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);
});
}
Run Code Online (Sandbox Code Playgroud)
我的问题是下一个:数组有类型的对象,消息和评论,如果数组有2个消息和3条评论,应该推到新阵列3的评论,并留下2个消息,但仅移动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]Run Code Online (Sandbox Code Playgroud)
这是一个如何完成它的例子:
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]Run Code Online (Sandbox Code Playgroud)
特定用例:
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--;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6899 次 |
| 最近记录: |