运行结果图以及思路:
1.首次判断是否是对象
2.Object.entries循环数据
3.循环里面的数据,对object,Array类型进行另外的处理
/**
* @description: 监测数据类型
* @param {*} type 可以支持的类型 'Undefined', 'String', 'Boolean', 'Array', 'Number', 'Null', 'Function'
* @return {*}
*/
const dataType = (data, type = 'Object') => {
let arr = ['Object', 'Undefined', 'String', 'Boolean', 'Array', 'Number', 'Null', 'Function']
if (!arr.includes(type)) {
console.warn(`输入的类型---${type}---不正确哦`)
}
return Object.prototype.toString.call(data) === `[object ${type}]`
}
/**
* @description: 判断是否为空
* @param {*} val
* @return {*}
*/
function isEmpty(val) {
if (val === '' || val === null || val === undefined) {
return true;
}
return false;
}
/**
* @description: 两个对象是否相等
* @param {*} obj1
* @param {*} obj2
* @return {*}
*/
function objCompare(obj1, obj2) {
let isTrueList = []
objectEqual(obj1, obj2)
function objectEqual(obj1, obj2, initObj = true) {
// 判断类型
if (!(dataType(obj1) && dataType(obj2)) && initObj) {
isTrueList.push(false)
return false
}
// 判断长度
if (Object.keys(obj1).length != Object.keys(obj2).length) {
isTrueList.push(false)
return
}
for (const [key, value] of Object.entries(obj1)) {
if (dataType(obj1[key])) {
objectEqual(obj1[key], obj2[key], false)
// 判断是否是数组
} else if (dataType(obj1[key], 'Array')) {
for (const [key1, value2] of Object.entries(obj1[key])) {
objectEqual(value2, obj2[key][key1], false)
}
} else {
if (isEmpty(obj2[key]) && isEmpty(value)) {
isTrueList.push(true)
} else {
obj2[key] && obj2[key] === value ? isTrueList.push(true) : isTrueList.push(false)
}
}
}
}
return isTrueList.every(item => item)
}
let arr1 = { id: 1, b: [{ id: 123, name: '' }], c: { id: { age: {name:1243} } } }
let arr2 = { id: 1, b: [{ id: 123, name: '' }], c: { id: { age: {name:123} } } }
console.log(objCompare(arr1, arr2))