One thing I hate dealing with is cloning JavaScript Objects. Well, deep cloning JavaScript Objects. So I decided to see if AI could write me a quick function.
And it did.
I asked ChatGPT “Can you write me a JavaScript function which will deep clone a JavaScript Object?”
And this was it’s response:
Certainly! You can create a deep clone function in JavaScript using recursion to clone nested objects and arrays. Here’s a sample function to deep clone a JavaScript object:
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
const cloneArr = [];
for (let i = 0; i < obj.length; i++) {
cloneArr[i] = deepClone(obj[i]);
}
return cloneArr;
}
const cloneObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key]);
}
}
return cloneObj;
}
You can use this deepClone
function to create a deep copy of a JavaScript object. Here’s an example of how to use it:
const originalObj = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'Exampleville',
},
};
const clonedObj = deepClone(originalObj);
console.log(clonedObj);
The clonedObj
will be a deep copy of the originalObj
, so you can modify it without affecting the original object.