3

I will give a simplified version of my two objects with nested objects inside them:

Object1:

{firstname: 'John', lastname: 'Cena', privateInfo: {privateProperty1: false, privateProperty2: true}}

Object2:

{firstname: 'John', middlename: 'Felix', lastname: 'Pina', privateInfo: {privateProperty1: true, privateProperty2: true} }

After comparing Object1 to Object2, I want to store all the different properties that Object2 has in a new object. In my case this will be:

let Object3 = {middlename: 'Felix', lastname: 'Pina', privateInfo: {privateProperty1: true}}

What would be the best and most efficient way to compare all properties of those objects (including nested ones and missing ones)?

In my case the properties of an object can reach up to 30-40. Efficiency is quite important here.

Smitherson
  • 373
  • 1
  • 4
  • 11
  • 1
    Possible duplicate of [Generic deep diff between two objects](https://stackoverflow.com/questions/8572826/generic-deep-diff-between-two-objects) – gaetanoM Aug 26 '18 at 22:12

1 Answers1

1

Just loop over the object keys and compare them to the other object. Since there could be nested object, a recursion is needed:

function difference(object, other) {
  var diff = {};
  for(var key in object) {
    if(typeof object[key] === "object" && typeof other[key] === "object" && object[key] && other[key]) {
      diff[key] = difference(object[key], other[key]);
    } else if(object[key] !== other[key]) {
      diff[key] = object[key];
    }
  }
  return diff;
}

Example:

function difference(object, other) {
  var diff = {};
  for(var key in object) {
    if(typeof object[key] === "object" && typeof other[key] === "object" && object[key] && other[key]) {
      diff[key] = difference(object[key], other[key]);
    } else if(object[key] !== other[key]) {
      diff[key] = object[key];
    }
  }
  return diff;
}

var object1 = {firstname: 'John', lastname: 'Cena', privateInfo: {privateProperty1: false, privateProperty2: true}};
var object2 = {firstname: 'John', middlename: 'Felix', lastname: 'Pina', privateInfo: {privateProperty1: true, privateProperty2: true} };

console.log(difference(object2, object1));

Note: If the nested objects are the same, their difference will be an empty object, which is logical.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73