EDIT: this was marked as a duplicate of a deep cloning question but my question (cf. title and last phrase) is about a way to tell if an object references itself, the deep cloning part is only there to provide context
I am trying to implement a function that will let me deep-copy a nested object without overwriting nested fields (I know lodash can solve this but I'd rather not use it of possible).
This is what I have written :
function copyObject(target, source) {
if (typeof target !== "object" || !target) {
throw 'target nust be a non-null javascript object';
}
Object.entries(source).map(([key, value]) => {
if (typeof value === "object"
&& typeof target[key] === "object"
&& target[key] !== null) {
copyObject(target[key], value);
} else {
target[key] = value;
}
})
return target;
}
the problem is this function would enter a infinite loop if its source parameter is an object that references itself like so (because it would always call itself on the c property of source) :
let src = {
a: "a",
b: "b",
}
src.c = src;
is there a way to know if a reference is part of an object ? I think in C this would be possible by looking at the memory addresses but in JS I don't know.