判斷兩個json是不是相等的
阿新 • • 發佈:2018-12-19
JavaScript判斷兩個json是不是相同的
原理
暴力的遞迴遍歷對比,遇到不相等就
return false
code:
let jsonObjA = {
"Name": "MyName",
"Company": "MyCompany",
"Infos": [{
"Age": "100"
}, {
"Box": [{
"Height": "100"
}, {
"Weight": "200"
}]
}],
"Address": "undefined"
};
let jsonObjB = {
"Name": "MyName",
"Company": "MyCompany",
"Infos": [{
"Age": "100"
}, {
"Box": [{
"Height": "100"
}, {
"Weight": "200"
}]
}],
"Address": "undefined"
};
function compreObj(obj1, obj2) {
var flag = true ;
function compre(obj1, obj2) {
if (Object.keys(obj1).length != Object.keys(obj2).length) {
flag = false;
} else {
for (let x in obj1) {
if (obj2.hasOwnProperty(x)) {
if (obj1[x] !== obj2[x]) {
compre (obj1[x], obj2[x]);
}
} else {
flag = false;
}
}
}
if (flag === false) {
return false;
} else {
return true;
}
}
return compre(obj1, obj2)
}
console.log(compreObj(jsonObjA, jsonObjB));