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

125
Visualizações
Why doesn't deep copy of array work using JavaScript?

I am trying to deep copy an array of objects but it doesn't work. I am using React, but here the problem is pure JavaScript.

const [selected, setSelected] = useState(value);

Value is value from parent component.

const onClickFunction = (arr) => {

    const newClonedArray = selected.map((a) => ({
        ...a
    }));
    // try to clone selected array 
    // i am also try with 
    // let clonedArray = JSON.parse(JSON.stringify(selected))
    // also no work

    const result = intersectionBy(arr, newClonedArray, "id");
    // here return only common items from two array using lodash library

    setSelected(result);

    console.log('selected  item right now should be changed', selected)
    // NO RESULT IS NOT CHANGED

    result.forEach((i) => {
        handleItemClick(i); // no important for now
    });
}

Inside the function I explained in detail what the problem was.

Why doesn't the array deep copy?

Selected state is array like ->

[
 { id : 1 , name: 'test' },
 { id : 2 , name: 'test 2' }
]

after deep copy i need to change selected array to be like ->

[
 { id : 1 , name: 'test' , title : 'title 1 ' },
 { id : 2 , name: 'test 2' , title : 'title 2 '  }
]

i just want to copy some values from some string.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to use Object.assign or JSON.stringify with JSON.parse

var selected = [
 { id : 1 , name: 'test' },
 { id : 2 , name: 'test 2' }
]

var newArray = JSON.parse(JSON.stringify(selected));

//do whatever you want to on newArray
newArray.map(a => a.title = a.name);

console.log("selected",selected)
console.log("newArray", newArray)

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