Skip to content

Instantly share code, notes, and snippets.

@Lynn-cc
Last active July 12, 2022 08:32
Show Gist options
  • Save Lynn-cc/9e0b3e72d05bcdf9134e6e651893f948 to your computer and use it in GitHub Desktop.
Save Lynn-cc/9e0b3e72d05bcdf9134e6e651893f948 to your computer and use it in GitHub Desktop.
Compare two JSON, output the first difference. 比较两个JSON对象,输出找到的第一个不同点的值及其父级堆栈值
function compare(o1, o2) {
const type1 = Array.isArray(o1) ? 'array' : typeof o1;
const type2 = Array.isArray(o2) ? 'array' : typeof o2;
if (!!o1 !== !!o2) {
console.log('Different boolean value', o1, o2);
return false;
}
if (type1 !== type2) {
console.log('Different type', o1, o2);
return false;
}
if (type1 === 'array') {
if (o1.length !== o2.length) {
console.log('Different array length', o1, o2);
return false;
}
o1.sort();
o2.sort();
return o1.every((v, i) => {
const ret = compare(v, o2[i]);
if (!ret) {
console.log('Different value in array', i, o1, o2);
}
return ret;
});
} else if (type1 === 'object') {
if (o1) {
const keys1 = Object.keys(o1).sort();
const keys2 = Object.keys(o2).sort();
if (keys1.length !== keys2.length) {
console.log('Different keys length', keys1, keys2);
return false;
}
return keys1.every((key, i) => {
const ret = keys2[i] === key && compare(o1[key], o2[key]);
if (!ret) {
console.log('Different key value of object', key, o1, o2);
}
return ret;
});
} else {
if (o1 !== o2) {
console.log('Different values', o1, o2);
return false;
}
return true;
}
}
if (o1 !== o2) {
console.log('Different values', o1, o2);
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment