0

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.

skpn
  • 89
  • 1
  • 5
  • 1
    This has been already answered in: https://stackoverflow.com/questions/40291987/javascript-deep-clone-object-with-circular-references – Jose Marin Jan 20 '21 at 17:57

1 Answers1

0

If I understand the question correctly, you should be good to go with the code bellow at the start of the .map func.

if( Object.is(value, source) ) { return }

MDN Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is

Object.is() determines whether two values are the same value. Two values are the same if one of the following holds...

  • both the same object (meaning both values reference the same object in memory)