Search code examples
javascriptjavascript-objects

Representing a JS objects reference by a string


I have a situation where I need to be able to compare if 2 objects are the same, but the comparison needs to be a string comparison.

To be clear, I cannot use const a = {}; a === a; to compare

The below function objectReferenceToString is what I am looking for, and it would behave as such:

const a = { foo: "bar" }
const b = { foo: "bar" }

console.log(objectReferenceToString(a) === objectReferenceToString(a)) // true
console.log(objectReferenceToString(a) === objectReferenceToString(b)) // false

Notice how the last console.log logs false. I do not want the string to represent the content of the object but it's reference.


Solution

  • Don't use a string to represent an object reference, use the object reference itself. Cheap and simple. a === a and a === b will give the desired results.

    If you do need this for some kind of serialisation (that should deserialise into the same object graph?), a WeakMap is the way to go:

    const refs = new WeakMap();
    let count = 0;
    function objectReferenceToString(obj) {
        let ref = refs.get(obj);
        if (!ref) refs.set(obj, ref = '$'+count++);
        return ref;
    }