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

403
Vistas
ReactJS - Duplicated objects in state array remain linked

I've reproduced the issue in the following codesandbox: https://codesandbox.io/s/unruffled-danilo-mbb0e?file=/src/App.js

I have a state array of objects [{name:"Tom"},{name:"Dick"},{name:"Harry"}]. I want to be able to duplicate the object present at a specific index in the array. I've provided a button "Duplicate" to do so in the sandbox.

Follow the following steps in the sandbox to recreate the issue:

  1. Click Duplicate under "Dick" to duplicate the Dick object in the state array
  2. Now click "change" under one of the two Dicks. Notice that my code only changes one "Dick" object in the state array, but the other duplicate one automatically gets changed.

I want to avoid this. I don't want the two Dick objects to remain linked forever. How do I do this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your'e shallow copying the array. You need to deep copy. Replace let copy = cur.slice(); with let copy = cur.map(item => {return {...item}}); and your code should work. basically we need to destructure the inner object to get a new copy of the every object in the array. You can read about this here Object Immutability in JS

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