Skip to content

Instantly share code, notes, and snippets.

@ascott1
Created May 12, 2014 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ascott1/d02ef9d2e29fad17e77f to your computer and use it in GitHub Desktop.
Save ascott1/d02ef9d2e29fad17e77f to your computer and use it in GitHub Desktop.
object comparison with recursion
var compare = function(a, b) {
"use strict";
// iterate over each key in b
for (var key in b) {
// check if the key is present in a
if (key in a) {
// make sure a and be are not exact matches
if (b[key] !== a[key]) {
if (typeof b[key] === "object") {
// if b[key] is an object recursively call compare
compare(a[key], b[key]);
} else {
// if not an exact match add to c
c[key] = b[key];
}
}
} else {
// if the key is not found add it to c
c[key] = b[key];
}
}
return c;
};
@polastre
Copy link

Consider looking into Javascript instanceof operator and toString function. That may help you determine the type of object that you're working with.

Also, what happens when you run this the first time? Is there anywhere that it would error out?

@ascott1
Copy link
Author

ascott1 commented May 13, 2014

Thanks @polastre!

Regarding the error, it would error if either a or b are not an object, so it would need to check that up front.

Something along the lines of:

var objCheck = function(a, b) {
  if ( a === null ||
       typeof a !== "object" ||
       b === null ||
       typeof b !== "object"
     ) {
    throw "Must compare two objects";
  } else {
    compare(a,b);
  }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment