我有两个带有键和值对的对象 obj1 和 obj2,我想比较 obj1 和 obj2 的值,如果两个对象相等,则返回 false,否则返回 true。
注意: obj1 和 obj2 之间缺少一些键,因此需要忽略这些键。
对于前- id 存在于 obj1 中但不存在于 obj2 中,因此忽略此键。
任何人都可以建议用更少的代码更好的方法来比较两个对象之间的值吗?
我尝试过以下代码
compareResponseAndFormValue(){
const result = JSON.stringify(this.obj1) === JSON.stringify(this.obj2);
console.log(result,"result")
}
预期产量
在下面的响应中,bankHoliday 列的值在 obj1 和 obj2 之间是不同的,所以它应该返回 true
以下是我的示例回复。
Const obj1 = {
"id": "",
"uom": "OOOUnits",
"classifiedHours": 720,
"entryType": "Monthly",
"entryDetails": {
"month": "April",
"year": 2024
},
"dataSource": "MDCS",
"availableTime": {
"bankHoliday": "8"
},
"valueOperatingTime": {
"breakDownTime": null
},
"operatingTime": {
"maintenanceTime": 0
},
"loadingTime": {
"nominalSpeed": "130"
},
"oeeCalculations": {
"others": {
"totalTime": 720
}
}
}
const obj2 =
{
"lineId": "E_A571_D",
"classifiedHours": null,
"entryDetails": {
"month": "April",
"year": 2024
},
"availableTime": {
"bankHoliday": "6.05"
},
"valueOperatingTime": {
"breakDownTime": null
},
"operatingTime": {
"maintenanceTime": 0
},
"loadingTime": {
"nominalSpeed": "130"
},
"oeeCalculations": {
"others": {
"totalTime": 720
}
},
"uom": "OOOUnits",
}
试试这个:
compateTwoObjects(x, y): boolean {
if (x === y) return true;
// if both x and y are null or undefined and exactly the same
if (!(x instanceof Object) || !(y instanceof Object)) return false;
// if they are not strictly equal, they both need to be Objects
if (x.constructor !== y.constructor) return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
for (var p in x) {
if (!x.hasOwnProperty(p)) continue;
// other properties were tested using x.constructor === y.constructor
if (!y.hasOwnProperty(p)) return false;
// allows to compare x[ p ] and y[ p ] when set to undefined
if (x[p] === y[p]) continue;
// if they have the same strict value or identity then they are equal
if (typeof (x[p]) !== "object") return false;
// Numbers, Strings, Functions, Booleans must be strictly equal
if (!this.compateTwoObjects(x[p], y[p])) return false;
// Objects and Arrays must be tested recursively
}
for (p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) return false;
// allows x[ p ] to be set to undefined
}
return true;
}