Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda