Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

401
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!