Created
January 11, 2017 12:12
-
-
Save nurbek-ab/d42f8bd55451f777b29ee35169cdd2d0 to your computer and use it in GitHub Desktop.
Show diff between two javascript objects
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
// http://stackoverflow.com/questions/31683075/how-to-do-a-deep-comparison-between-2-objects-with-lodash | |
function compare(a, b) { | |
var result = { | |
different: [], | |
missing_from_first: [], | |
missing_from_second: [] | |
}; | |
_.reduce(a, function (result, value, key) { | |
if (b[key] != undefined) { | |
if (_.isEqual(value, b[key])) { | |
return result; | |
} else { | |
if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) { | |
//dead end. | |
result.different.push(key); | |
return result; | |
} else { | |
var deeper = compare(a[key], b[key]); | |
result.different = result.different.concat(_.map(deeper.different, (sub_path) => { | |
return key + "." + sub_path; | |
})); | |
result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => { | |
return key + "." + sub_path; | |
})); | |
result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => { | |
return key + "." + sub_path; | |
})); | |
return result; | |
} | |
} | |
} else { | |
result.missing_from_second.push(key); | |
return result; | |
} | |
}, result); | |
_.reduce(b, function (result, value, key) { | |
if (a[key] != undefined) { | |
return result; | |
} else { | |
result.missing_from_first.push(key); | |
return result; | |
} | |
}, result); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment