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

100
Views
Scoping of variable inside a javascript map
{charts.map( (ch, i) => {
   const tempApiDetails = {...apiDetails};
   tempApiDetails.apiOptions.params = generateParams(ch.dashBoardType, ch.reportType); 
   //above line is to generate params for API call

   <SimpleTable apiOptions={tempApiDetails} />
})}

in the above code the charts is having 3 items. but all three in the end is having the same params which is made for the last chart in the charts variable. Can somebody explain me what will be underlying principle for it?

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

0

This has nothing to do with scope.

tempApiDetails is a shallow copy of apiDetails.

This means the value of tempApiDetails.apiOptions is the same each time it goes around the loop.

Since it is an object, and objects are stored by reference, every time you assign to apiOptions.params you are overwriting the params of the same object.

You need to make a clone of apiOptions.

const tempApiDetails = {
    ...apiDetails,
    apiOptions: {...apiDetails.apiOptions}
};

And you can do the whole thing in one go:

const tempApiDetails = {
    ...apiDetails,
    apiOptions: {
         ...apiDetails.apiOptions,
         params: generateParams(ch.dashBoardType, ch.reportType)
    }
};

For complex data structures you might want to look at the immer library which will take care of all the cloning for you.

const tempApiDetails = produce(apiDetails, draft => {
    draft.apiOptions.params = generateParams(ch.dashBoardType, ch.reportType);
});
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!