티스토리 뷰

JSON.stringify 을 사용하지 않고 두 Object가 같은지 비교(deep-equal)

 

 


 

Deep Equality checking of Two Objects

function compareObjectsDeepEqual(original, target) {
  const isObject = obj => typeof obj === "object" && obj !== null;

  if (!isObject(original) || !isObject(target)) {
    return original === target;
  }

  const keysOfOriginal = Object.keys(original);
  const keysOfTarget = Object.keys(target);

  if (keysOfOriginal.length !== keysOfTarget.length) {
    return false;
  }

  for (let key of keysOfOriginal) {
    if (!keysOfTarget.includes(key)) {
      return false;
    }

    if (isObject(original[key])) {
      if (!compareObjectsDeepEqual(original[key], target[key])) {
        return false;
      }
    } else {
      if (original[key] !== target[key]) {
        return false;
      }
    }
  }

  return true;
}

 

 


 

🔽 테스트 케이스들

  1. empty : const original = {}, target = {} ▶ true

  2. falsy value : const original = { name: "" }, target = { name: 0 } ▶ false

  3. nested ▶ true

    const original = {
      name: "Judy",
      work: {
        company: "zootopia",
        since: { year: 2017, month: 1, day: 1 },
      },
    };
    const target = {
      name: "Judy",
      work: {
        company: "zootopia",
        since: { year: 2017, month: 1, day: 1 },
      },
    };
  1. null : const original = { name: null }, target = { name: null }) ▶ true

  2. Array : ▶ true

    const original = { name: "Judy", array: ["0", "1", "2"] };
    const target = { name: "Judy", array: ["0", "1", "2"] };
  1. Array + Type of value ▶ false

    const original = { name: "Judy", array: ["0", "1", "2"] };
    const target = { name: "Judy", array: [0, 1, 2] };
  2. Do not check for a property in the object's prototype chain ▶ false

    Object.prototype.test = "Don't check me!";
    
    const original = { name: "Judy", test: "Don't check me!" };
    const target = { name: "Judy" };
  1. Complex nested object + array ▶ true

    const original = {
     name: "Judy",
     array: [{ A: "apple", B: ["beer", "blue"] }],
     string: "STRING ",
    };
    const target = {
     name: "Judy",
     array: [{ A: "apple", B: ["beer", "blue"] }],
     string: "STRING ",
    };
  1. Order of original and target (Two-way)
    const original = original, target) ▶ false
    const original = target, original) ▶ false

    const original = {
      A: "apple",
      B: ["beer", "blue"],
    };
    const target = {
      A: "apple",
    };
댓글