Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda