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

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

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 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!