Created
May 12, 2014 23:49
-
-
Save ascott1/d02ef9d2e29fad17e77f to your computer and use it in GitHub Desktop.
object comparison with recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
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
Consider looking into Javascript
instanceof
operator andtoString
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?