Skip to content

Instantly share code, notes, and snippets.

@ascott1
Created May 12, 2014 23:49
Show Gist options
  • 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;
};
@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