user2133404
user2133404

Reputation: 1857

javascript compare all attributes of an object with other object

I have two objects A

var A = {
    a: 1,
    b: 2,
    c: 3,
    d: {
        0: {
            e: 4,
            f: 5
        },
        1: {
            g: 6
        }
    }
};

var B = {
    a: 1,
    b: 9,
    c: 3,
    d: {
        0: {
            e: 4,
            f: 8
        }
    }
};

I want to compare all attributes in B with corresponding attributes in A, if present. Return if their values doesn't match.

so I want to return

   b: 9,
    d:{
       0: {
          f: 8
       }
    }

Is there a simple soluton for this in lodash way?

EDIT : I tried Object.keys for A and B, did a intersection and then compare each key value. Its failing when I have nested attributes.

Upvotes: 1

Views: 515

Answers (1)

potatosalad
potatosalad

Reputation: 4887

Here is a basic function that uses lodash to detect changes in simple nested objects and arrays. It is by no means comprehensive, but it works well for simple changesets.

function changes (a, b) {
  if (_.isEqual(a, b)) {
    return;
  } else {
    if (_.isArray(a) && _.isArray(b)) {
      return _.reduce(b, function(array, value, index) {
        value = changes(a[index], value);
        if (!_.isUndefined(value)) {
          array[index] = value;
        }
        return array;
      }, []);
    } else if (_.isObject(a) && _.isObject(b)) {
      return _.reduce(b, function(object, value, key) {
        value = changes(a[key], value);
        if (!_.isUndefined(value)) {
          object[key] = value;
        }
        return object;
      }, {});
    } else {
      return b;
    }
  }
}

Here is an example of it in action: http://plnkr.co/edit/drMyGDAh2XP0925pBi8X?p=preview

Upvotes: 1

Related Questions