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

148
Visualizações
Javascript: Reassigned variable being mutated

Any idea why my variable assignment is being mutated? This seems like something simple but I'm just not sure what's going on.

Below, an object of data is passed into the pullChecklist function as a prop. I want to take this data, create a copy (newPage), change the ids in that copy and then save the copy in state.

However, whenever I try and change the ids in the copy newPage, the ids also change in page. This is confirmed by the 3 console logs.

If I remove the if statement all together and just leave the Original Assignment and Original Assignment 2 console logs, the data is exactly as when it is sent as a prop. Adding the if statement mutates all the console logs to the version with updated ids.

const pullChecklist = (page) => {
    console.log('Original Assignment', page.components[0].blocks)
    let newPage = page
    if (newPage.components[0].blocks) {

      newPage.components[0].blocks.map((block) => {
        if (block.type === 'checklist') {
        
          let newTest = uuidv4()
          block.id = newTest

          for (const c in block.data) {
            let newId = uuidv4()
            block.data[c].id = newId
          }
          console.log('Reformatted', block);
        }
      });
    }
    console.log('Original Assignment 2', page.components[0].blocks);

  };

Why is the data from page being mutated? Thank you!

EDIT:

As pointed out by @Vlaz below, let newPage = page does not copy the object.

I used: obj = JSON.parse(JSON.stringify(o)); in order to properly copy the object.

about 4 years ago · Juan Pablo Isaza
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