JS对比两个对象的值是否相等,并且可以排除不想对比的键值对。
在项目中,我们需要判断用户是否对表单内的内容做过修改,假设有两种场景,一是用户新增的时候,二是用户修改的时候。
无论是用户修改还是新增,我们都可以拿到表单内的初始数据,使用vue项目来说, 我们可以使用
this.$options.data().XXX//来拿到初始数据
this.XXX//拿到修改后的数据,这时候就需要对这两组数据进行对比
一、不排除里面的键,直接对比
JSON.stringify(XXX)==JSON.stringify(XXX)
// 转成字符串直接对比,但是有的浏览器可能支持的不是很好, 比较推荐第二种方法
二、排除一些键,对比部分
//json 与 json2的option6数组的b值不相同 nest 与nest 2的最里层不相同 options 与options2的dra不相同
let json = {
option: 123,
option1: '123',
option2: {
option: 12
},
option3: [
1, 2, 3
],
option4: {
a: {
a: 1
},
b: {
a: 1
}
},
option5: {
a: [1, 2, 3],
b: [1, 2, 3]
},
option6: [{
a: 1,
b: 2
},
{
a: 1,
b: 2
},
]
}
let json2 = {
option: 123,
option1: '123',
option2: {
option: 12
},
option3: [
1, 2, 3
],
option4: {
a: {
a: 1
},
b: {
a: 1
}
},
option5: {
a: [1, 2, 3],
b: [1, 2, 3]
},
option6: [{
a: 1,
b: 3
},
{
a: 1,
b: 2
},
]
}
let nest = {
a: {
a: [{
a: {
a: [{
a: [1]
}]
}
}]
}
}
let nest2 = {
a: {
a: [{
a: {
a: [{
a: [2]
}]
}
}]
}
}
let options = {
dra: false,
str: 1,
num: 2
}
let options2 = {
dra: true,
str: 1,
num: 2
}
//核心代码来了↓
function comparison() {
let bl = true
return function main(data1, data2, arr = []) {
if (!bl) {
return bl
}
if (typeof data1 == 'object') {
if (Array.isArray(data1)) {
for (let i = 0; i < data1.length; i++) {
main(data1[i], data2[i],arr)
}
} else {
for (let key in data1) {
if (arr.indexOf(key) == -1) {
main(data1[key], data2[key],arr)
} else {
continue
}
}
}
} else {
bl = data1 == data2
}
return bl
}
}
//核心代码来了 ↑
let fn = comparison()
//let jsonResult = fn(json, json2, ['option6']) //true
//let jsonResult2 = fn(json, json2) //false
//let nestResult = fn(nest, nest2) // false
//let nestResult2 = fn(nest, nest2, ["a"])//true
//let optionsResult = fn(options, options2) // false
//let optionsResult = fn(options, options2, ['dra']) // true
//这边是使用闭包定义了一个bl变量 来记录是否改变, 使用递归逐层对比,想尝试的小伙伴记得点个赞哦
/* 第三个参数,数组里面喊着 不想做对比的键,尝试的小伙伴需要一条一条去验证,因为闭包的原因,
两条一起试的话如果上一条结果为假则会将bl置为假并且保留下来。所有尝试一条就注释一条哦。
记得双击,么么哒
*/