UNPKG

deep-compare-objects

Version:

Deeply compare objects and identify their differences.

60 lines 2.5 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = deepCompareObjects; const json_stringify_safe_1 = __importDefault(require("json-stringify-safe")); /** * Finds and returns the differences between two objects `a` and `b`. * * @param {Record<string, any>} [a] The first object to compare. * @param {Record<string, any>} [b] The second object to compare. * * @returns {Record<string, any> | undefined} An object containing the differences between `a` and `b`, or undefined if `b` is null or undefined. */ function deepCompareObjects(a = {}, b = {}) { // This event happens when the object b is of the null type. if (!b) { return b; } return [...new Set([...Object.keys(b), ...Object.keys(a)])].reduce((differences, key) => { if (Array.isArray(b[key])) { if (!Array.isArray(a[key])) { return { ...differences, [key]: b[key] }; } const d = b[key].reduce((acc, item, index) => { const isObject = typeof item === "object" && !Array.isArray(item); if (!isObject && (0, json_stringify_safe_1.default)(a[key][index]) === (0, json_stringify_safe_1.default)(item)) { return acc; } acc !== null && acc !== void 0 ? acc : (acc = []); if (isObject) { const d = deepCompareObjects(a[key][index], item); if (d && Object.keys(d).length) { acc[index] = d; } } else { acc[index] = item; } return acc; }, undefined); if (d && d.length) { differences[key] = d; } } else if (typeof b[key] === "object") { const d = deepCompareObjects(a[key], b[key]); if ((d && Object.keys(d).length) || (0, json_stringify_safe_1.default)(a[key]) !== (0, json_stringify_safe_1.default)(b[key])) { differences[key] = d; } } else if ((0, json_stringify_safe_1.default)(a[key]) !== (0, json_stringify_safe_1.default)(b[key])) { differences[key] = b[key]; } return differences; }, {}); } //# sourceMappingURL=index.js.map