Last active
January 18, 2016 16:36
-
-
Save zaus/cd2ae7636b350b17e6ab to your computer and use it in GitHub Desktop.
Simple javascript comparison of two objects with console logging/warning when different
This file contains hidden or 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
/** | |
* Compare versions of objects and warn of differences | |
* @param {object} v1 variant 1 | |
* @param {object} v2 variant 2 | |
* @param {bool} stringify optionally (if provided and `true`) stringify the variant parameters when dumping | |
* @param {string} root [internal use] nested key placeholder | |
* @example <caption>Example comparing two things:</caption> | |
* // should result in warnings for 'foo' and 'somebool' | |
* compObj({foo: "bar", id: 123, somebool: true}, {bar: "foo", id: 123, somebool: 'true'}); | |
* @returns {void} nothing -- see console logging | |
*/ | |
function compObj(v1, v2, stringify, root) { | |
// only the stuff in the first version | |
for(var k in v1) if(v1.hasOwnProperty(k)) { | |
// nested properties | |
if( typeof v1[k] === typeof {} ) compObj(v1[k], v2[k], false, (!root ? k : root + '.' + k) + '.'); | |
// normal properties | |
else console[ v1[k] == v2[k] ? 'info' : 'warn' ](!root ? k : root + k, v1[k] == v2[k], v1[k], v2[k]); | |
} | |
// wanna see the whole thing? how to dump... | |
if(stringify) console.log(JSON.stringify(v1, null, 2), JSON.stringify(v2, null, 2)); | |
else if(stringify !== false) console.log(v1, v2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment