SoFunction
Updated on 2025-04-03

JS depth determines that the two object fields are the same

Code:

/**
 * Determine whether this object is of Object type
 * @param {Object} obj
 */
function isObject(obj){
return (obj)==='[object Object]';
};
/**
 * Determine whether this type is Array type
 * @param {Array} arr
 */
function isArray(arr){
return (arr)==='[object Array]';
};
/**
 * Depth comparison: whether two objects are the same
 * @param {Object} oldData
 * @param {Object} newData
 */
function equalsObj(oldData,newData){
// If the type is a basic type, return true if the sameif(oldData===newData)return true;
if(isObject(oldData)&&isObject(newData)&&(oldData).length === (newData).length){
// Type is an object and the number of elements is the same// traverse all attributes in all objects to determine whether the elements are the samefor (const key in oldData) {
if ((key)) {
if(!equalsObj(oldData[key],newData[key]))
// There are different properties in the object. Return falsereturn false;
}
}
}else if(isArray(oldData)&&isArray(oldData)&&===){
// Type is an array and the array length is the samefor (let i = 0,length=; i <length; i++) {
if(!equalsObj(oldData[i],newData[i]))
// If the array element has different elements, return falsereturn false;
}
}else{
// All other types return falsereturn false;
}
// Go here, it means that all elements in the array or object are the same, return truereturn 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
}
]
}
];
(equalsObj(oldArr,newArr));

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.