Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

That is because when you write const tbl2 = tbl1;, it doesn't clone the array, rather takes a reference to the original. So when you modify the the reference, the original gets modified as well.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!