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.
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)