forked from UKSOURCE/cms.hailearning.edu.vn
41 lines
1.0 KiB
JavaScript
41 lines
1.0 KiB
JavaScript
function diffObject(before = {}, after = {}, parentPath = "") {
|
|
const changes = [];
|
|
|
|
const allKeys = new Set([
|
|
...Object.keys(before || {}),
|
|
...Object.keys(after || {}),
|
|
]);
|
|
|
|
for (const key of allKeys) {
|
|
const beforeValue = before?.[key];
|
|
const afterValue = after?.[key];
|
|
const currentPath = parentPath ? `${parentPath}.${key}` : key;
|
|
|
|
// Nếu cả hai đều là object (không phải array)
|
|
if (
|
|
typeof beforeValue === "object" &&
|
|
typeof afterValue === "object" &&
|
|
beforeValue !== null &&
|
|
afterValue !== null &&
|
|
!Array.isArray(beforeValue) &&
|
|
!Array.isArray(afterValue)
|
|
) {
|
|
changes.push(...diffObject(beforeValue, afterValue, currentPath));
|
|
continue;
|
|
}
|
|
|
|
// So sánh primitive hoặc array
|
|
if (JSON.stringify(beforeValue) !== JSON.stringify(afterValue)) {
|
|
changes.push({
|
|
field: currentPath,
|
|
before: beforeValue,
|
|
after: afterValue,
|
|
});
|
|
}
|
|
}
|
|
|
|
return changes;
|
|
}
|
|
|
|
module.exports = diffObject;
|