Lodash工具比较两个{}对象是否有变化

import isEqual from 'lodash/isEqual';

const obj1 = { key1: 'value1', key2: 'value2' };
const obj2 = { key1: 'value1', key2: 'value2' };
const obj3 = { key1: 'value1', key2: 'value3' };

// 使用 isEqual 比较两个对象
console.log(isEqual(obj1, obj2)); // true,因为内容相同
console.log(isEqual(obj1, obj3)); // false,因为内容不同

 

function deepEqual(obj1: any, obj2: any): boolean {
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object') {
    return obj1 === obj2;
  }

  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  for (const key of keys1) {
    if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
      return false;
    }
  }

  return true;
}

const obj1 = { key1: 'value1', key2: 'value2' };
const obj2 = { key1: 'value1', key2: 'value2' };
const obj3 = { key1: 'value1', key2: 'value3' };

console.log(deepEqual(obj1, obj2)); // true
console.log(deepEqual(obj1, obj3)); // false

你可能感兴趣的:(前端,javascript,vue.js)