How to implement deep copy without using recursion, JSON.parse \ JSON.stringify, structuredClone(). There can be any number of elements in an object.
const data1 = {
a: 10,
y: null,
k: [1, 2],
b: 3,
c: {
d: 4,
e: {
w: 50,
u: undefined,
s: {
f: {
v: 5,
},
},
},
},
};
const data2 = [
{
a: 10,
y: null,
k: [1, 2],
b: 3,
c: {
d: 4,
e: {
w: 50,
u: undefined,
s: {
f: {
v: 5,
},
},
},
},
};
];
In my example, I can't implement a deep copy, I just stop at the second loop. How can we avoid recursion and other ready-made solutions?
function deepCopy(dataType) {
const copy = {};
let data = dataType;
if (Array.isArray(data)) {
data = dataType[0];
}
for (const [key, value] of Object.entries(data)) {
if (typeof data[key] === "object") {
copy[key] = Array.isArray(data[key]) ? [] : value;
for (let deepKey in data[key]) {
copy[key][deepKey] = data[key][deepKey];
}
} else {
copy[key] = data[key];
}
}
return copy;
}
If you use a stack and and a reference lookup map, you can iterate through the structure without any recursion.
Here is a breakdown of the algorithm:
Check if the input is an object (including arrays), if not, return it directly.
Initialize a stack with an entry containing the source (the input object) and a target (a new object or array of the same type).
Create a reference map to keep track of original objects and their corresponding copies.
While the stack is not empty:
Pop an item from the stack, which includes a source object and its corresponding target copy.
Iterate over all the keys in the source object:
If the value associated with the key is an object (including arrays):
If the value is not an object, assign it directly to the corresponding key in the target object.
Return the copy of the input object from the reference map.