UNPKG

es-toolkit

Version:

A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.

46 lines (45 loc) 1.71 kB
import { noop } from "../../function/noop.mjs"; import { mergeWith } from "./mergeWith.mjs"; //#region src/compat/object/merge.ts /** * Merges the properties of one or more source objects into the target object. * * This function performs a deep merge, recursively merging nested objects and arrays. * If a property in the source object is an array or object and the corresponding property in the target object is also an array or object, they will be merged. * If a property in the source object is `undefined`, it will not overwrite a defined property in the target object. * * The function can handle multiple source objects and will merge them all into the target object. * * @param object - The target object into which the source object properties will be merged. This object is modified in place. * @param sources - The source objects whose properties will be merged into the target object. * @returns The updated target object with properties from the source object(s) merged in. * * @example * const target = { a: 1, b: { x: 1, y: 2 } }; * const source = { b: { y: 3, z: 4 }, c: 5 }; * * const result = merge(target, source); * console.log(result); * // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } * * @example * const target = { a: [1, 2], b: { x: 1 } }; * const source = { a: [3], b: { y: 2 } }; * * const result = merge(target, source); * console.log(result); * // Output: { a: [3], b: { x: 1, y: 2 } } * * @example * const target = { a: null }; * const source = { a: [1, 2, 3] }; * * const result = merge(target, source); * console.log(result); * // Output: { a: [1, 2, 3] } */ function merge(object, ...sources) { return mergeWith(object, ...sources, noop); } //#endregion export { merge };