xxxxxxxxxx
/* The structuredClone method allows you to deep clone a object including its
keys and values. */
const person = {
name: 'Mehedi Islam',
skills: ['javascript','react','c#','node'],
dob: new Date('2001-01-19')
}
const person2 = structuredClone(person);
person2.name = 'Ripon';
console.log(person.name); // Mehedi Islam
console.log(person2.name); // Ripon
// As you see in the above code altering person2.name did not alter person.name.
xxxxxxxxxx
const myDeepCopy = structuredClone(myOriginal);
or
const myDeepCopy = JSON.parse(JSON.stringify(myOriginal));
xxxxxxxxxx
const dude = { name: 'jeff', weapons: { main: 'sword', alt: 'bat' } };
const bruh = structuredClone(dude);
xxxxxxxxxx
let ingredients_list = ["noodles", { list: ["eggs", "flour", "water"] }];
let ingredients_list_deepcopy = JSON.parse(JSON.stringify(ingredients_list));
// Change the value of the 'list' property in ingredients_list_deepcopy.
ingredients_list_deepcopy[1].list = ["rice flour", "water"];
// The 'list' property does not change in ingredients_list.
console.log(ingredients_list[1].list);
// Array(3) [ "eggs", "flour", "water" ]
xxxxxxxxxx
function copy(arr1, arr2) {
for (var i =0; i< arr1.length; i++) {
arr2[i] = arr1[i];
}
}
copy(arr1, arr2)