javascript 中的对象比较看似复杂。虽然比较数字和字符串等原始值很简单,但比较对象可能会导致意想不到的结果。让我们探索不同的对象比较方法,并构建一个强大的解决方案来检测对象之间的变化。
当开发人员第一次遇到 javascript 中的对象比较时,他们经常尝试这样的操作:
const user1 = { name: "john", age: 30 }; const user2 = { name: "john", age: 30 }; console.log(user1 === user2); // false
令人惊讶的是,即使两个对象具有相同的内容,这也会返回 false。发生这种情况是因为 javascript 比较的是对象引用,而不是它们的值。两个对象都指向内存中的不同位置。
比较对象的快速方法是使用 json.stringify:
const areequal = (obj1, obj2) => json.stringify(obj1) === json.stringify(obj2); console.log(areequal(user1, user2)); // true
虽然这适用于简单的情况,但它有局限性:
让我们创建一个更复杂的解决方案,不仅可以检测差异,还可以告诉我们发生了什么变化:
function getobjectdiff(original, current) { const changes = {}; // check current object's properties for (const [key, value] of object.entries(current)) { if (!(key in original)) { changes[key] = { oldvalue: undefined, newvalue: value }; continue; } const originalvalue = original[key]; const currentvalue = value; // handle different types of comparisons if ( originalvalue !== currentvalue && string(originalvalue) !== string(currentvalue) && json.stringify(originalvalue) !== json.stringify(currentvalue) ) { changes[key] = { oldvalue: originalvalue, newvalue: currentvalue }; } } // check for removed properties for (const key of object.keys(original)) { if (!(key in current)) { changes[key] = { oldvalue: original[key], newvalue: undefined }; } } return object.keys(changes).length === 0 ? null : changes; }
此实现:
这种类型的对象比较对于以下情况特别有用:
const originalForm = { name: "John", email: "john@example.com" }; const currentForm = { name: "John", email: "john.doe@example.com" }; console.log(getObjectDiff(originalForm, currentForm)); // Output: { email: { oldValue: "john@example.com", newValue: "john.doe@example.com" } }
ps:这是一个 github 要点,用于比较和获取两个对象之间的差异的简单函数:
以上就是如何比较(差异)两个对象的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号