Home > OS >  Not able to copy a array data to another array
Not able to copy a array data to another array

Time:05-26

I'm trying to copy data from one array to another for manipulation.

Below is the code

let data=[];
this.dataArray.length=0;
this.dataArray=[];
for(var i=0;i<this.test.length;i  ){
  data.push(this.test[i]);
}
data.forEach((element)=>{
  let Config=element.config;
  Config.forEach((config)=>{
    let obj=this.formatMap(config.Map,config.operation);
    delete config.Map;
    config["Map"]=obj;
  })
  delete element.isExpand
  delete element.name
})
console.log(data);
console.log(this.test);

Basically in the original array Map is an array , and in the data array I want it to be an object to send it to the api.

The original array is also getting modified.

I know we can use spread operator also but my tslib is not updated and hence I can't do that.

I have also used splice operator to create the data array for the test array. console log for both the array shows that the original array is also getting modified,

Below is the error in console which confirms that the original array is also getting modified.

Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Please Guide. Thanks

CodePudding user response:

you can use this code:

 let array1=[1,2,3,4,5,6];
let array2: number[]=[];

array1.forEach(item=>{
  array2.push(item);
});

or

 let array1=[{code:1,name:"a"},{code:2,name:"b"},{code:3,name:"c"},{code:4,name:"d"}];
let array2: any[]=[];

array1.forEach(item=>{
  array2.push(item);
});

CodePudding user response:

You can just do this, it is named spread operator and it is very useful, so you don't need to loop in the array and push every single element.

let array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(array1);
let array2 = [...array1]
console.log(array2);

This is just a simple example, you must adapt it to your needs.

  • Related