Skip to content

Commit c7c6c0f

Browse files
faberchridreamorosisvozza
authored
fix(commons): don't overwrite existing value with undefined in deepMerge (#5141)
Co-authored-by: Andrea Amorosi <dreamorosi@gmail.com> Co-authored-by: Stefano Vozza <svozza@amazon.com>
1 parent 0143158 commit c7c6c0f

2 files changed

Lines changed: 36 additions & 5 deletions

File tree

packages/commons/src/deepMerge.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,9 @@ const mergeArrayItemsByIndex = (
4545
}
4646

4747
// Otherwise, replace the target item with source item
48-
targetArray[i] = srcItem;
48+
if (srcItem !== undefined || tgtItem === undefined) {
49+
targetArray[i] = srcItem;
50+
}
4951
}
5052
};
5153

@@ -123,7 +125,9 @@ const mergeRecursive = (
123125
continue;
124126
}
125127

126-
target[key] = sourceValue;
128+
if (sourceValue !== undefined || targetValue === undefined) {
129+
target[key] = sourceValue;
130+
}
127131
}
128132
};
129133

packages/commons/tests/unit/deepMerge.test.ts

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -428,16 +428,43 @@ describe('Function: deepMerge', () => {
428428
expect(result).toEqual({ a: null });
429429
});
430430

431-
it('handles undefined values in source', () => {
431+
it('handles undefined values in source (does not overwrite existing value with `undefined`)', () => {
432432
// Prepare
433433
const target = { a: 1, b: 2 };
434-
const source = { a: undefined };
434+
const source = { a: undefined, c: undefined };
435435

436436
// Act
437437
const result = deepMerge(target, source);
438438

439439
// Assess
440-
expect(result).toEqual({ a: undefined, b: 2 });
440+
expect(result).toStrictEqual({ a: 1, b: 2, c: undefined });
441+
});
442+
443+
it('handles undefined values in array of source (does not overwrite existing value with `undefined`)', () => {
444+
// Prepare
445+
const target = { arr: [4, 5, 6] };
446+
const source = { arr: [1, undefined, 3, undefined] };
447+
source.arr[1] = undefined;
448+
449+
// Act
450+
const result = deepMerge(target, source);
451+
452+
// Assess
453+
expect(result).toStrictEqual({ arr: [1, 5, 3, undefined] });
454+
});
455+
456+
it('handles missing values in array of source (does not overwrite existing value with `undefined`)', () => {
457+
// Prepare
458+
const target = { arr: [4, 5, 6] };
459+
const source = { arr: new Array(4) };
460+
source.arr[0] = 1;
461+
source.arr[2] = 3;
462+
463+
// Act
464+
const result = deepMerge(target, source);
465+
466+
// Assess
467+
expect(result).toStrictEqual({ arr: [1, 5, 3, undefined] });
441468
});
442469

443470
it('handles Symbol keys (ignores them)', () => {

0 commit comments

Comments
 (0)