Compare 2 objects and remove/add keys to object B

I’m trying to compare the structure of 2 objects (recursively/nested).

Object’s A structure should shape the structure of object B.

If they key exist in both objects, keep the existing key value in object B.

If object B does not contain a certain key that object A contains, it should be added with its value.
If object B contains a key that object A does not, it should be removed from object B.

I have found several code snippets that compares structures but creates a new object with the missing key/values, but what I’m trying to achieve is to actually change the structure of the object B by adding missing key/values or removing keys that shouldn’t be there.

  objA: {
    object1: {
      key1: "key1",
    },

    addObject2: {
      key1: "key1",
      key2: "key2",
      subObj1: {
        sub1: "sub1",
      },
    },
  },

  objB: {
    object1: {
      key1: "key1",
      key2: "key2",
    },
  },

Structural changes

  • objA.addObject2 should be added to objB.
  • objB.Object1.key2 should be removed from objB

Desired outcome

 objB: {
    object1: {
      key1: "key1",
    },

    addObject2: {
      key1: "key1",
      key2: "key2",
      subObj1: {
        sub1: "sub1",
      },
    },
  },

41 thoughts on “Compare 2 objects and remove/add keys to object B”