如何将对象列表复制到另一个[Typescript]

时间:2019-07-19 08:46:18

标签: angular typescript-typings

我只想将价值从“全部”复制到“可用”,有时我也无法从可用中获取价值。

我尝试了多种方法,例如slice()Array.from()=,但这是行不通的

let a = [{"key":66,"value":"MAAA","username":"MAZA007"},{"key":66,"value":"MAAA","username":"MAZA007"}];

let all = a
let available = all

变量中没有值

这是我的全部功能

          protected  async processMoverBox(projectId?:number) {


            let available;
            let all;

            if(projectId != undefined)    
            {

                let projectTeamId =  await this.restful.get("api/operation/S200100/allprojectteam/"+projectId); 
                    console.log(projectTeamId)

                     all = projectTeamId.map((id) => {return this.copy(this.allUser.find(allUser => allUser.key == id))})

            }  
            else{ all = this.copy(this.allUser); console.log(this.allUser)}
            console.log(all);

            let a = [{"key":66,"value":"MAAA","username":"MAZA007"},{"key":66,"value":"MAAA","username":"MAZA007"}]


            available = [...a];

            console.log(available);
            console.log(JSON.stringify(available, null, 4));

            if(this.selected.length>0){
            this.selected.forEach((ms)=>{
                available.splice(available.findIndex(e => e.key == ms.key), 1);
            })
             }

             console.log(available);
             console.log(this.selected)

            this.memberDualbox.initMoveBox(available, this.selected, all)
            this.memberDualbox.disabled = this.isViewMode;
    }

4 个答案:

答案 0 :(得分:2)

您可以像下面的示例一样分配值。

let a = [{"key":66,"value":"MAAA","username":"MAZA007"},{"key":66,"value":"MAAA","username":"MAZA007"}];

let all = a
let available = Object.assign({}, all);

答案 1 :(得分:1)

您的代码正在运行。

但是,您的代码不是从分配给变量“ a”的数组中“复制”数据。您正在执行的操作是创建其他变量“ all”和“ available”,这些变量均通过引用值指向内存中的同一数组。数组是参考值类型。如果要创建阵列的全新副本/克隆,则可以使用多种技术。按照上面的@uminder,您可以使用slice创建浅表副本。

let available = all.slice(0);

或者您可以使用传播语法:

let available = [...all];

完整示例:

(function() {

    const a = [{
        "key": 66,
        "value": "MAAA",
        "username": "MAZA007"
    }, {
        "key": 66,
        "value": "MAAA",
        "username": "MAZA007"
    }];

    const all = a;

    //Returns true (same reference)
    console.log(all === a);

    const available = [...all];

    //Returns false (new reference)
    console.log(available === a);

    //Alterntive syntax example shallow copy
    //let available = all.slice(0);

    console.log(JSON.stringify(available, null, 4));
}
)();

答案 2 :(得分:0)

如果需要创建副本数组,可以执行以下操作: 让all = a.map(val => val); 都获得克隆数组,但是数组'a'不变;

也可以使用.concat()方法;

答案 3 :(得分:0)

if(this.selected.length>0){
  this.selected.forEach((ms)=>{
    available.splice(available.findIndex(e => e.key == ms.key), 1);
  })
}

为什么不

const available = all.filter(e => this.selected.some(ms => e.key === m.key));