[英]Object's Deep Compare
I wrote this function to deeply compare two objects in JavaScript 我编写了此函数以深入比较JavaScript中的两个对象
Equal: function(obj1, obj2) {
var keys1 = Object.keys(obj1).sort();
var keys2 = Object.keys(obj2).sort();
if (keys1.length !== keys2.length) {
return false;
}
// first make sure have same keys.
if (!keys1.every(function(k, i) {
return (k === keys2[i]);
})) {
return false;
}
return keys1.every(function(kk) {
var v1 = obj1[kk];
var v2 = obj2[kk];
if (Array.isArray(v1)) {
return this.EqualArr(v1, v2);
} else if (typeof v1 === "object" && v1 !== null) {
return this.Equal(v1, v2);
} else {
return v1 === v2;
}
});
},
But I got this error: 但是我得到了这个错误:
Cannot convert undefined or null to object
无法将未定义或null转换为对象
The problem happens at this line: 问题发生在此行:
var keys2 = Object.keys(obj2).sort();
Can anyone help me ? 谁能帮我 ?
The problem here is the invocation to Object.keys
这里的问题是对
Object.keys
的调用
This method does not accept null
or undefined
as argument. 此方法不接受
null
或undefined
作为参数。 To avoid that you can check objects passed are not falsy. 为避免这种情况,您可以检查传递的对象是否虚假。
if (!obj1 && !obj2) {
return false
}
Since you're already using the UI5 framework, you can make use of the built-in comparator jQuery.sap.equal
. 由于您已经在使用UI5框架,因此可以使用内置的比较器
jQuery.sap.equal
。
jQuery.sap.equal(a, b, maxDepth?, contains?)
jQuery.sap.equal(a,b,maxDepth ?, contains?)
Compares the two given values for equality, especially takes care not to compare arrays and objects by reference, but compares their content.比较两个给定的值是否相等,尤其要注意不要通过引用比较数组和对象,而是比较它们的内容。
Here is an example: 这是一个例子:
sap.ui.require([ "jquery.sap.global" ], jQuery => console.log(jQuery.sap.equal({ a: "I'm A", b: { property: "I'm B", c: { property: "I'm C", array: [1, 2, 3], date: new Date("2018-02-28"), }, }, }, { a: "I'm A", b: { property: "I'm B", c: { property: "I'm C", array: [1, 2, 3], date: new Date("2018-02-28"), }, }, }))); console.clear();
<script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.