0

I have the following two objects that will always have the same number / name of fields:

var a = {
           c: 25,
           field1: 10,
           field2: 20,
           field3: "x"
         }

var b = {
           c: 25,
           field1: 10,
           field2: 22,
           field3: "y"
         }

Is there a way that I can have put into a variable if there are changes to the fields so I have a variable to show this that contains text something like:

var changes = "field2: 20 > 22,  field3: x > y"

What I think I need to do is to somehow iterate through the values of each field and compare but I am not sure how to do that with Javascript.

  • Do you want to put the differences between the values into another object? – Nivas Jun 04 '14 at 15:46
  • I just want to log the differences into a variable. I hope it makes sense. –  Jun 04 '14 at 15:50
  • Might be more appropriate to do this in the event that updates said fields. when the field is updated, log the previous value and the new value. – Kevin B Jun 04 '14 at 15:53

1 Answers1

0

Using How do I loop through or enumerate a JavaScript object?, loop through the properties and compare it to the properties in the other object:

for (var key in a) {
  if (a.hasOwnProperty(key)) {   
      if(b[key] != a[key]) {
          //values are are different, handle difference
      }
  }
}

The hasOwnProperty check is to make sure we are not handling properties from the prototype of the object. this may or may not be relevant depending on how your objects are built and used.

Note that onder versions of IE8 do not support hasOwnProperty.

Community
  • 1
  • 1
Nivas
  • 18,126
  • 4
  • 62
  • 76