Any idea why my variable assignment is being mutated? This seems like something simple but I'm just not sure what's going on.
Below, an object of data is passed into the pullChecklist
function as a prop. I want to take this data, create a copy (newPage
), change the ids in that copy and then save the copy in state.
However, whenever I try and change the ids in the copy newPage
, the ids also change in page
. This is confirmed by the 3 console logs.
If I remove the if statement all together and just leave the Original Assignment
and Original Assignment 2
console logs, the data is exactly as when it is sent as a prop. Adding the if statement mutates all the console logs to the version with updated ids.
const pullChecklist = (page) => {
console.log('Original Assignment', page.components[0].blocks)
let newPage = page
if (newPage.components[0].blocks) {
newPage.components[0].blocks.map((block) => {
if (block.type === 'checklist') {
let newTest = uuidv4()
block.id = newTest
for (const c in block.data) {
let newId = uuidv4()
block.data[c].id = newId
}
console.log('Reformatted', block);
}
});
}
console.log('Original Assignment 2', page.components[0].blocks);
};
Why is the data from page
being mutated? Thank you!
EDIT:
As pointed out by @Vlaz below, let newPage = page
does not copy the object.
I used: obj = JSON.parse(JSON.stringify(o));
in order to properly copy the object.