-1

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

Shruti Nair
  • 1,982
  • 8
  • 30
  • 57
  • 2
    Here are the ways you can copy an array. https://www.freecodecamp.org/news/how-to-clone-an-array-in-javascript-1d3183468f6a/ For your case, you will need to use deep copy. See, 8. JSON.parse and JSON.stringify – Md Wahidul Azam May 26 '22 at 08:24
  • Does this answer your question? [Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop](https://stackoverflow.com/questions/3978492/fastest-way-to-duplicate-an-array-in-javascript-slice-vs-for-loop) Also see: [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Yogi May 26 '22 at 08:50
  • Thanks.i used the JSON.parse method and it worked. – Shruti Nair May 26 '22 at 09:00

2 Answers2

0

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

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.

AhmedSHA256
  • 525
  • 2
  • 20