Javascript Object Prototype Compare Object for equality

Description

Javascript Object Prototype Compare Object for equality


// Lets create an object with a few properties
let myNewObject = { property1:213, property2: true, property3: "Hello World", bla:null};

// Lets create another object with the same properties
let myNewObject2 = { property1:213, property2: true, property3: "Hello World", bla:null};

Object.prototype.isSame = function(cObj) {
    let result = true;
    if (cObj) {/*from   w w w .  ja va2  s  .co  m*/
        // Go one direction
        for (let key in cObj) {
            if (cObj[key])
                if (!this[key] || (cObj[key] != this[key])) {
                    result = false;
                    break;
                }
        }
        if (result == true) {
            // now go the other direction
            for (let key in this) {
                if (this[key])
                    if (!cObj[key] || (this[key] != cObj[key])) {
                        result = false;
                        break;
                    }
            }      
        }
    } else result = false;
    return result;
}

console.log(  myNewObject.isSame(myNewObject2)); // true

myNewObject2.expandoProperty = "I'm new!";

console.log(  myNewObject.isSame(myNewObject2) ); // false



PreviousNext

Related