JS 找到前后两个数组的改变项

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;
};

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值