Search code examples
javascript

Comparing two similar objects (holding same keys) and returning key value pairs that are different


I currently have two objects that look like the following:

   const initialValues= { name: "Robert Terrell", email: "[email protected]" }
   const formData = { name: 'New Name', email: 'new email' }

I am attempting to compare the two objects with the same keys. I would like to take the initialValues and use them as a reference to compare against the formData. If the formData has different values pertaining to a particular key I would like to return those key value pairs from formData. in this case, both name: 'New Name' and email: 'new email' would be returned. I'm having trouble really wrapping my mind around how to get into a deep comparison of the two objects. I know I can loop through each object and grab their key value pairs using a for loop like so:

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

but in regards to comparing the key value pairs I'm a bit stuck. any and all suggestions would be much appreciated.


Solution

  • Loop through one object, then compare its values with the corresponding element of the other.

    const initialValues= { name: "Robert Terrell", email: "[email protected]" };
    const formData = { name: 'New Name', email: 'new email' };
       
    for (const [key, value] of Object.entries(initialValues)) {
        if (value != formData[key]) {
            console.log(`${key}: ${value} != ${formData[key]}`);
        }
    }