Judge that two object fields are the same through JS depth

Time:2019-11-13

Code:

/**
*Determine whether this object is of object type
* @param {Object} obj 
*/
function isObject(obj){
return Object.prototype.toString.call(obj)==='[object Object]';
};
/**
*Determine whether this type is array type
* @param {Array} arr 
*/
function isArray(arr){
return Object.prototype.toString.call(arr)==='[object Array]';
};
/**
*Depth compares whether two objects are the same
* @param {Object} oldData 
* @param {Object} newData 
*/
function equalsObj(oldData,newData){
//Returns true if the type is basic
if(oldData===newData)return true;
if(isObject(oldData)&&isObject(newData)&&Object.keys(oldData).length === Object.keys(newData).length){
//Type is object and the number of elements is the same
//Traverse all attributes in all objects to determine whether the elements are the same
for (const key in oldData) {
if (oldData.hasOwnProperty(key)) {
if(!equalsObj(oldData[key],newData[key]))
//Object with different properties returns false
return false;
}
}
}else if(isArray(oldData)&&isArray(oldData)&&oldData.length===newData.length){
//Type is array and array length is the same
for (let i = 0,length=oldData.length; i <length; i++) {
if(!equalsObj(oldData[i],newData[i]))
//Returns false if there are different elements in an array element
return false;
}
}else{
//Other types, return false
return false;
}
//Go here to show that all elements in the array or object are the same, and return true
return true;
};

Test:

var oldArr = [1,2,
[
{
Name: "Zhang San",
age:11,
}
],
{
Name: 'Li Si',
age:21,
em:[
{
Address: 'Handan',
phone:'123'
},
{
Address: 'Beijing',
phone:234
}
]
}
];
var newArr = [1,2,
[
{
Name: "Zhang San",
age:11
}
],
{
Name: 'Li Si',
age:21,
em:[
{
Address: 'Handan',
phone:'123'
},
{
Address: 'Beijing',
phone:234
}
]
}
];
console.log(equalsObj(oldArr,newArr));

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.