# 2628. JSON Deep Equal ###### tags: `leetcode 30 days js challenge` `Medium` [2628. JSON Deep Equal](https://leetcode.com/problems/json-deep-equal/) ### 題目描述 Given two objects `o1` and `o2`, check if they are **deeply equal**. For two objects to be **deeply equal**, they must contain the same keys, and the associated values must also be **deeply equal**. Two objects are also considered **deeply equal** if they pass the `===` equality check. You may assume both objects are the output of `JSON.parse`. In other words, they are valid JSON. Please solve it without using lodash's `_.isEqual()` function. ### 範例 **Example 1:** ``` Input: o1 = {"x":1,"y":2}, o2 = {"x":1,"y":2} Output: true Explanation: The keys and values match exactly. ``` **Example 2:** ``` Input: o1 = {"y":2,"x":1}, o2 = {"x":1,"y":2} Output: true Explanation: Although the keys are in a different order, they still match exactly. ``` **Example 3:** ``` Input: o1 = {"x":null,"L":[1,2,3]}, o2 = {"x":null,"L":["1","2","3"]} Output: false Explanation: The array of numbers is different from the array of strings. ``` **Example 4:** ``` Input: o1 = true, o2 = false Output: false Explanation: true !== false ``` **Constraints**: - 1 <= `JSON.stringify(o1).length` <= 10<sup>5</sup> - 1 <= `JSON.stringify(o2).length` <= 10<sup>5</sup> - `maxNestingDepth <= 1000` ### 解答 #### TypeScript ```typescript= function areDeeplyEqual(o1: any, o2: any): boolean { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (typeof o1 !== typeof o2) return false; if (Array.isArray(o1) !== Array.isArray(o2)) return false; if (typeof o1 === 'object') { const o1Keys = Object.keys(o1); const o2Keys = new Set(Object.keys(o2)); if (o1Keys.length !== o2Keys.size) return false; for (const key of o1Keys) { if (!o2Keys.has(key)) return false; if (!areDeeplyEqual(o1[key], o2[key])) return false; } return true; } return false; } ``` > [name=Sheep][time=Sun, May 21, 2023] ### Reference [回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)