UNPKG

@mikezimm/fps-library-v2

Version:

Library of reusable typescript/javascript functions, interfaces and constants

62 lines (60 loc) 2.24 kB
/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Per Bing Chat * Sure, I can help you with that. There are different ways to deep merge two JSON objects in TypeScript, depending on your needs and preferences. Here are some possible solutions: You can use a third-party library such as ts-deepmerge that provides a deep merge function that automatically infers the return type based on your input, without mutating the source objects1. You can use the Object.assign () method or the spread operator (…) to shallow merge the objects, and then use a recursive function to merge the nested properties2. For example: * @param item * @returns */ // A recursive function to deep merge two objects export function mergeDeep(target, source, skips = []) { if (isObject(target) && isObject(source)) { for (const key in source) { if (skips.indexOf(key) > -1) { // Do nothing // target[key] = source [key]; } else if (isObject(source[key])) { if (!target[key]) Object.assign(target, { [key]: {} }); mergeDeep(target[key], source[key], skips); } else { Object.assign(target, { [key]: source[key] }); } } } return target; } // A helper function to check if an item is an object function isObject(item) { return (item && typeof item === 'object' && !Array.isArray(item)); } // function test( showLog = true ) { // const start = new Date() // // Example usage // const obj1 = { a: { b: 1, c: 2 }, d: 3 }; // const obj2 = { a: { b: 4, e: 5 }, f: 6, x: JSON.parse(JSON.stringify( obj1 )) }; // let merged = {}; // for (let i = 0; i < 1000000; i++) { // merged = mergeDeep (obj1, obj2); // } // const end = new Date() // if ( showLog === true ) { // console.log (merged); // { a: { b: 4, c: 2, e: 5 }, d: 3, f: 6 } // console.log( 'time:', end - start ) // } // } // test() // result : // { // "a": { // "b": 4, // "c": 2, // "e": 5 // }, // "d": 3, // "f": 6, // "x": { //# sourceMappingURL=mergeDeep.js.map