In the JS front-end interview process, often encounter such a written question: JS in how to compare two JSON objects are equal to the instance code, the following small make up some time for everyone to clean up, together to see.
1. Prepare three tool methods to determine whether it is an object type or an array, 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": "M"},
{
"box" : [
{"Height": "M"},
{"Weight": "[]}
]
}"
,
"address": "Horse Bar Mountain"
}
var JSONOBJB = {
' Name ': ' MyName ', ' Company
': ' MyCompany ',
' infos ': [
{' Age ': '} ',
{
' Box ": [
{" Height ":" Second "},
{" Weight ":" ["}
]
}
],
" address ":" Horse Hill Mountain # "
}
3. The main code
function Compare (Obja, OBJB) {
if (!isobj (obja) | | |!isobj (OBJB)) return false;//Determine whether the type is correct
if (GetLength (obja)!= g Etlength (OBJB)) return false; Determines whether the length is consistent return
compareobj (Obja, OBJB, true);//default to True
}
function Compareobj (obja, OBJB, flag) {
for (var key in Obja) {
if (!flag)//jump out of the entire loop break
;
if (!objb.hasownproperty (key)) {flag = false; break;}
if (!isarray (Obja[key])) {//child is not an array, compare property value
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)//Here jumps out of the loop in order not to let recursion continue to break
;
Flag = Compareobj (Oa[k], ob[k], flag);
}} return flag;
}
4. Calling methods
var result = Compare (Jsonobja, JSONOBJB);
Console.log (result); True or False