Home > Software engineering >  How to create a function that check if two objects have the same properties? [javascript]
How to create a function that check if two objects have the same properties? [javascript]

Time:01-23

How can I create a function that return true if all the properties in two objects are the same? I have come up with the following code which will return true if at least one of the properties are the same. However if one of the properties are different, it should return false. Bear in mind that I'm in the learning process of JavaScript...Thank you!

function BuildAddress(street, city, zipCode) {
  this.street = street;
  this.city = city;
  this.zipCode = zipCode;
}

const address1 = new BuildAddress('a', 'b', 101);
const address2 = new BuildAddress('a', 'b', 101);

function areEqual(address1, address2) {
  for (let key in address1)
    for (let value in address2)
  if (address1[key] === address2[value]) return true;
  return false;
}

CodePudding user response:

Here is an example of a function that compares two objects and returns true if all of their properties are the same: `

function areObjectsEqual(obj1, obj2) {
    // get the properties of each object
    const obj1Props = Object.getOwnPropertyNames(obj1);
    const obj2Props = Object.getOwnPropertyNames(obj2);
    // check if the number of properties is different
    if (obj1Props.length !== obj2Props.length) {
        return false;
    }
    // iterate over each property and compare the values
    for (let i = 0; i < obj1Props.length; i  ) {
        const propName = obj1Props[i];
        if (obj1[propName] !== obj2[propName]) {
            return false;
        }
    }
    return true;
}

`

CodePudding user response:

to check two object is equal or not.

const objectsEqual = (o1, o2) => 
      typeof o1 === 'object' && Object.keys(o1).length > 0 ? 
        Object.keys(o1).length === Object.keys(o2).length 
          && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
        : o1 === o2;


function BuildAddress(street, city, zipCode) {
 this.street = street;
 this.city = city;
 this.zipCode = zipCode;
}

const address1 = new BuildAddress('a', 'b', 101);
const address2 = new BuildAddress('a', 'b', 101);

console.log(objectsEqual(address1, address2))

CodePudding user response:

You can compare sorted keys array. Part of my solution is based on this question: How to check if two arrays are equal with JavaScript?

function BuildAddress(street, city, zipCode) {
    this.street = street;
    this.city = city;
    this.zipCode = zipCode;
}


function areEqual(a, b) {
    let arrA = Object.keys(a).sort()
    let arrB = Object.keys(b).sort()
    return arraysEqual(arrA, arrB)
}

function arraysEqual(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false;
    if (a.length !== b.length) return false;


    for (var i = 0; i < a.length;   i) {
        if (a[i] !== b[i]) return false;
    }
    return true;
}

const address1 = new BuildAddress('a', 'b', 101);
const address2 = new BuildAddress('a', 'b', 101);
const address3 = {spam:"foo"}

console.log(areEqual(address1, address2)) //true
console.log(areEqual(address1, address3)) //false

CodePudding user response:

There are multiple ways of achieving it, for example.

Method 1 using JSON.stringfy

function compareObjects(obj1, obj2) {
  return JSON.stringify(obj1) === JSON.stringify(obj2);
}

Method 2 using recursion

function isEqual(a, b) {
    if (a === b) return true;
    if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
    if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
    if (a.prototype !== b.prototype) return false;
    let keys = Object.keys(a);
    if (keys.length !== Object.keys(b).length) return false;
    return keys.every(k => isEqual(a[k], b[k]));
}

Method 3 using combination of Object.keys() and loop

function compareObjects(obj1, obj2) {
  const obj1Keys = Object.keys(obj1);
  const obj2Keys = Object.keys(obj2);

  if (obj1Keys.length !== obj2Keys.length) {
    return false;
  }

  for (let i = 0; i < obj1Keys.length; i  ) {
    if (obj1[obj1Keys[i]] !== obj2[obj1Keys[i]]) {
      return false;
    }
  }

  return true;
}

Note that Method 1 and Method 2 will work for nested properties too, while Method 3 will work only for top level properties.

Hope that helps.

  • Related