const obj1 = {
standardStates: ["20"],
dates: ["2"],
standardClasses: ["50781e3b1e524b505f174cde1b75d385"],
};
const obj2 = {
standardStates: ["20"],
dates: ["2", "3"],
standardClasses: ["50781e3b1e524b505f174cde1b75d385"],
};
const getDiffValue = (obj1, obj2) => {
let data;
// 通过entires转为键值对数组
const arr1 = Object.entries(obj1);
const arr2 = Object.entries(obj2);
//拼接后推入set中,但是需要将数组转为json字符串否则无法对比值的一致性
const arr = arr1.concat(arr2).map((item) => JSON.stringify(item));
const result = Array.from(new Set(arr)).map((item) => JSON.parse(item));
//裁剪掉第一个对象占用掉的部分,剩下就是第二个对象与其不同的属性部分
result.splice(0, arr1.length);
//将键值对数组转为正常对象
const obj = Object.fromEntries(result);
return obj;
};
console.log("getDiffValue", getDiffValue(obj1, obj2)); // {dates: ['2', '3']}
2. 查找数组新增或删除的值
let oldValue = [1,2,3];
let newValue = [1,2,3,4];
function findArrDiff(oldValue,newValue){
let set
let diff
let type
if(newValue.length > oldValue.length){
console.log('add')
type = 'add'
set = new Set(oldValue);
diff = newValue.filter(v=>!set.has(v));
}else{
console.log('delete')
type = 'delete'
set = new Set(newValue);
diff = oldValue.filter(v=>!set.has(v));
}
return {diff,type}
}
findArrDiff(oldValue,newValue) // output: { diff: [4], type: "add" }
3. 知道是否是重置,找到具体改变的 changedKey,及单项改变时的改变值
export const getDiffValue = (obj1, obj2) => {
let data = {};
// 通过entires转为键值对数组
const arr1 = Object.entries(obj1);
const arr2 = Object.entries(obj2);
//拼接后推入set中,但是需要将数组转为json字符串否则无法对比值的一致性
const arr = arr1.concat(arr2).map((item) => JSON.stringify(item));
const result = Array.from(new Set(arr)).map((item) => JSON.parse(item));
//裁剪掉第一个对象占用掉的部分,剩下就是第二个对象与其不同的属性部分
result.splice(0, arr1.length);
//将键值对数组转为正常对象
const obj = Object.fromEntries(result);
if (Object.keys(obj).length) {
const changedKey = Object.keys(obj);
const res = findArrDiff(obj1[changedKey[0]], obj2[changedKey[0]]);
data = { diffKey: res.diff[0], changedKey, isReset: changedKey.length > 1 };
}
return data;
};