UNPKG

@andranik-arakelyan/js-utilities

Version:
61 lines (60 loc) 2.13 kB
/** * Type of difference found when comparing JSON objects */ export type JsonDiffType = 'missing_key' | 'extra_key' | 'type_mismatch'; /** * Represents a single difference found during JSON comparison */ export interface JsonDifference { /** Index of the compared object (0-based) */ objectIndex: number; /** Type of difference found */ diffType: JsonDiffType; /** Path to the key that has the difference (dot notation) */ keyPath: string; /** Type of value in base object (if key exists) */ baseValueType?: string; /** Type of value in compared object (if key exists) */ comparedValueType?: string; } /** * Compares a base JSON object with multiple other JSON objects and returns differences. * * This function performs a deep comparison between a base JSON object and one or more * comparison objects, identifying missing keys, extra keys, and type mismatches. * * @param base - The base JSON object to compare against * @param comparisons - Array of JSON objects to compare with the base * @returns Array of differences found during comparison * * @example * ```ts * const base = { * name: "John", * age: 30, * address: { city: "NYC", zip: "10001" } * }; * * const obj1 = { * name: "John", * address: { city: "NYC" } * }; // missing 'age' and 'address.zip' * * const obj2 = { * name: "John", * age: "30", * address: { city: "NYC", zip: "10001" }, * email: "john@example.com" * }; // 'age' type mismatch, extra 'email' * * const differences = jsonCompare(base, [obj1, obj2]); * console.log(differences); * // [ * // { objectIndex: 0, diffType: 'missing_key', keyPath: 'age', baseValueType: 'number' }, * // { objectIndex: 0, diffType: 'missing_key', keyPath: 'address.zip', baseValueType: 'string' }, * // { objectIndex: 1, diffType: 'type_mismatch', keyPath: 'age', baseValueType: 'number', comparedValueType: 'string' }, * // { objectIndex: 1, diffType: 'extra_key', keyPath: 'email', comparedValueType: 'string' } * // ] * ``` */ export declare function jsonCompare(base: any, comparisons: any[]): JsonDifference[];