| 1 | import { ConfigMergeType } from "../index.js"; |
| 2 | |
| 3 | type JsonObject = { [key: string]: any }; |
| 4 | |
| 5 | export function mergeJson( |
| 6 | first: JsonObject, |
| 7 | second: JsonObject, |
| 8 | mergeBehavior?: ConfigMergeType, |
| 9 | mergeKeys?: { [key: string]: (a: any, b: any) => boolean }, |
| 10 | ): any { |
| 11 | const copyOfFirst = JSON.parse(JSON.stringify(first)); |
| 12 | |
| 13 | try { |
| 14 | for (const key in second) { |
| 15 | const secondValue = second[key]; |
| 16 | |
| 17 | if (!(key in copyOfFirst) || mergeBehavior === "overwrite") { |
| 18 | // New value |
| 19 | copyOfFirst[key] = secondValue; |
| 20 | continue; |
| 21 | } |
| 22 | |
| 23 | const firstValue = copyOfFirst[key]; |
| 24 | if (Array.isArray(secondValue) && Array.isArray(firstValue)) { |
| 25 | // Array |
| 26 | if (mergeKeys?.[key]) { |
| 27 | // Merge keys are used to determine whether an item form the second object should override one from the first |
| 28 | const keptFromFirst: any[] = []; |
| 29 | firstValue.forEach((item: any) => { |
| 30 | if ( |
| 31 | !secondValue.some((item2: any) => mergeKeys[key](item, item2)) |
| 32 | ) { |
| 33 | keptFromFirst.push(item); |
| 34 | } |
| 35 | }); |
| 36 | copyOfFirst[key] = [...keptFromFirst, ...secondValue]; |
| 37 | } else { |
| 38 | copyOfFirst[key] = [...firstValue, ...secondValue]; |
| 39 | } |
| 40 | } else if ( |
| 41 | typeof secondValue === "object" && |
| 42 | typeof firstValue === "object" |
| 43 | ) { |
| 44 | // Object |
| 45 | copyOfFirst[key] = mergeJson(firstValue, secondValue, mergeBehavior); |
| 46 | } else { |
| 47 | // Other (boolean, number, string) |
| 48 | copyOfFirst[key] = secondValue; |
| 49 | } |
| 50 | } |
| 51 | return copyOfFirst; |
| 52 | } catch (e) { |
| 53 | console.error("Error merging JSON", e, copyOfFirst, second); |
| 54 | return { |
| 55 | ...copyOfFirst, |
| 56 | ...second, |
| 57 | }; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | export default mergeJson; |