将对象从一个数组移动到另一个数组 [英] Move object from one array to another

查看:150
本文介绍了将对象从一个数组移动到另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,其中一个属性是一个对象数组,想法是在一个条件为真时将对象从该数组移动到没有新对象。

i have one object that one of the properties is an array of objects, the idea is to move objects from that array to no new one if one condition is true.

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

the problem that i have is the next one: the array has to types of objects, messages and comments, if the array has 2 messages and 3 comments it should push to the new array 3 comments and leave 2 messages, but is moving only 2 comments.

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

Any idea. Thanks for your help.

推荐答案

这就是这样做的方式:

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]

这是一个例子如何做到这一点:

This is an example of how it can be done:

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--;
  }
}

这篇关于将对象从一个数组移动到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆