javascriptfunctionargumentscomparisonobject-comparison

Concept: Comparing objects and arrays like atrings and numbers in JavaScript


Is there a way to compare two un-referenced objects by their literal value like a string or a number?

_is = function (a, b) { /* Code */ }

This could apply to any object type, even custom objects.

_is(new X("a"), new X("a")); // Returns True;

_is(new X("a"), new Y("a")); // Returns False

You could convert it into a string, but that would be sloppy.

JSON.stringify({ x: "a" }) == JSON.stringify({ x: "a" }); // Returns True

Maybe there's a way to programatically read each key, subkey, and value of the object, and compare that way.

Any ideas?


Solution

  • Javascript hashes objects in memory with unique memory pointers. You're essentially creating two separate objects, and trying to compare them. Despite the fact that they look similar, they in fact are different.

    Try storing the object as a variable first, and then testing against that variable.

    pass = arg => { return arg }; pass({ a: "x" }); // Returns The Input
    
    pass(({ a: "x" })) == ({ a: "x" }); // Returns False
    
    var obj = {a: "x"};
    
    pass(obj) === (obj); // Returns true
    
    console.log(pass(obj) === (obj));

    UPDATE:

    If you want to compare two separate objects, the best and most efficient way I've found is to create a hash of both objects, and then compare the hashes (basically comparing two checksums). If the hashes match, the objects are the same. If the hashes differ, they are different objects. You can assume that the properties and values are the same in each object, since using a hashing function, even hashing functions used in some forms of crypto like md5 and sha can be utilized to generate a unique hash of the object.

    Here's a 3rd Party Library I've used before to generate object hashes.