How to Compare Two Json Objects for Equality Instance Code in JS
- 2021-07-02 23:36:27
- OfStack
In the front-end interview process of js, we often encounter such a pen test: How to compare two Json objects in JS to see if they are equal to the instance code. Take some time for everyone to sort out this site below, and take a look at it.
1. Prepare three tool methods to judge whether it is an object type, whether it is an array, and get the length of the object
function isObj(object) {
return object && typeof (object) == 'object' && Object.prototype.toString.call(object).toLowerCase() == "[object object]";
}
function isArray(object) {
return object && typeof (object) == 'object' && object.constructor == Array;
}
function getLength(object) {
var count = 0;
for (var i in object) count++;
return count;
}
2. Prepare two identical or different Json objects
var jsonObjA = {
"Name": "MyName",
"Company": "MyCompany",
"Infos": [
{ "Age": "100" },
{
"Box": [
{ "Height": "100" },
{ "Weight": "200" }
]
}
],
"Address": " Malan Mountain "
}
var jsonObjB = {
"Name": "MyName",
"Company": "MyCompany",
"Infos": [
{ "Age": "100" },
{
"Box": [
{ "Height": "100" },
{ "Weight": "200" }
]
}
],
"Address": " Malan Mountain 2 No. "
}
3. Main code
function Compare(objA, objB) {
if (!isObj(objA) || !isObj(objB)) return false; // Determine whether the type is correct
if (getLength(objA) != getLength(objB)) return false; // Judge whether the length is 1 To
return CompareObj(objA, objB, true);// Default to true
}
function CompareObj(objA, objB, flag) {
for (var key in objA) {
if (!flag) // Jump out of the whole loop
break;
if (!objB.hasOwnProperty(key)) { flag = false; break; }
if (!isArray(objA[key])) { // When the child is not an array , Compare attribute values
if (objB[key] != objA[key]) { flag = false; break; }
} else {
if (!isArray(objB[key])) { flag = false; break; }
var oA = objA[key], oB = objB[key];
if (oA.length != oB.length) { flag = false; break; }
for (var k in oA) {
if (!flag) // The reason for jumping out of the loop here is to prevent recursion from continuing
break;
flag = CompareObj(oA[k], oB[k], flag);
}
}
}
return flag;
}
4. Call the method
var result = Compare(jsonObjA, jsonObjB);
console.log(result); // true or false