diff --git a/src/compat/object/mergeWith.spec.ts b/src/compat/object/mergeWith.spec.ts index e9db3d7c0..9a5194558 100644 --- a/src/compat/object/mergeWith.spec.ts +++ b/src/compat/object/mergeWith.spec.ts @@ -116,4 +116,26 @@ describe('mergeWith', () => { expect(mergeWith(target, undefined, noop)).toBe(target); expect(mergeWith(target, 1, noop)).toBe(target); }); + + it('should work with nullish variables', () => { + const source = { a: 1 }; + expect(mergeWith(null, source, noop)).toEqual(source); + expect(mergeWith(undefined, source, noop)).toEqual(source); + expect(mergeWith(null, undefined, source, noop)).toEqual(source); + expect(mergeWith(null, undefined, noop)).toEqual({}); + expect(mergeWith(undefined, null, noop)).toEqual({}); + }); + + it('should merge array to a null prop', () => { + const target = { a: null }; + const source = { a: ['abc', '123'] }; + expect(mergeWith(target, source, noop)).toEqual({ a: ['abc', '123'] }); + }); + + it('should return an object when the target is a primitive', () => { + expect(mergeWith(1, null, noop)).toEqual(Object(1)); + expect(mergeWith('a', null, noop)).toEqual(Object('a')); + expect(mergeWith(true, null, noop)).toEqual(Object(true)); + expect(mergeWith(1, { a: 1 }, noop)).toEqual(Object.assign(1, { a: 1 })); + }); }); diff --git a/src/compat/object/mergeWith.ts b/src/compat/object/mergeWith.ts index ac169149a..2201d467a 100644 --- a/src/compat/object/mergeWith.ts +++ b/src/compat/object/mergeWith.ts @@ -1,5 +1,6 @@ import { cloneDeep } from './cloneDeep.ts'; import { clone } from '../../object/clone.ts'; +import { isPrimitive } from '../../predicate/isPrimitive.ts'; import { getSymbols } from '../_internal/getSymbols.ts'; import { isArguments } from '../predicate/isArguments.ts'; import { isObjectLike } from '../predicate/isObjectLike.ts'; @@ -360,7 +361,9 @@ export function mergeWith(object: any, ...otherArgs: any[]): any { source: any, stack: Map ) => any; - + if (isPrimitive(object)) { + object = Object(object); + } let result = object; for (let i = 0; i < sources.length; i++) { @@ -423,7 +426,7 @@ function mergeWithDeep( } if (Array.isArray(sourceValue)) { - if (typeof targetValue === 'object') { + if (typeof targetValue === 'object' && targetValue !== null) { const cloned: any = []; const targetKeys = Reflect.ownKeys(targetValue);