Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Seeking explanation forEach javascript

I am working with the following array of objects and I am trying to run a function with forEach. However, I don’t want to destroy the original tbl1. Hence, I made a copy of tbl1 in tbl2 and I am running forEach on tbl2.

What surprises me, if I run a forEach on tbl2 so that I can preserve the tbl1 structure, it also takes place in tbl1 which I don’t want.

const tbl1 = [{ "Month": 1, "Value": 100 }, { "Month": 2, "Value": 200 }, { "Month": 3, "Value": 300 }]

const tbl2 = tbl1;

tbl2.forEach(
    (d)=>{d.newCol=d.Month*152;});

console.log(tbl1,tbl2);

Is it possible to run forEach on a copy table without destroying the source table?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use map

const tbl1 = [{ "Month": 1, "Value": 100 }, { "Month": 2, "Value": 200 }, { "Month": 3, "Value": 300 }]

const tbl2 = tbl1.map(d => {
  return {
   ...d,
   newCol: d.Month*152
  }
})


console.log(tbl1,tbl2);

If you want to do a deep copy you should use JSON.parse and JSON.stringify

const tbl1 = [{ "Month": 1, "Value": 100 }, { "Month": 2, "Value": 200 }, { "Month": 3, "Value": 300 }]

const tbl2 = JSON.parse(JSON.stringify(tbl1));

tbl2.forEach(
    (d)=>{d.newCol=d.Month*152;});

console.log(tbl1,tbl2);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading